Lodash 从一个集合创建一个集合

Lodash create a collection from a collection

我有以下数据结构;

var data = [{
    "username": "admin",
    "update": "19/07/2015 17:44:14"
}, {
    "username": "admin",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:44:14"
}];

使用 lodash 库,我想创建以下数据结构;

var newData = [{
    "username": "admin",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:00"
}];

如您所见,我需要删除重复的名称并仅存储最近的日期。如有任何帮助,我们将不胜感激,

您可以使用 orderBy() to order the collection by the update date value in descending order and then use uniqBy() 删除重复值。

var data = [{
    "username": "admin",
    "update": "19/07/2015 17:44:14"
}, {
    "username": "admin",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:44:14"
}];

var result = _(data)
  .orderBy(v => new Date(v.update), 'desc')
  .uniqBy('username')
  .value();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.12.0/lodash.min.js"></script>

更新

我注意到 update 日期值不符合作为参考的 IETF-compliant RFC 2822 timestamps and version of ISO8601 date formats, check Date documentation。因此,上述解决方案不适用于 最近日期 标准。

你有两种选择来解决这个问题:

  1. 更改从源(后端或您从中获取的任何资源)格式化 update 日期值的方式。这样上面的解决方案仍然适用。

  2. 在运行时间转换日期格式。解决方案如下所示:

var data = [{
    "username": "admin",
    "update": "19/07/2015 17:44:14"
}, {
    "username": "admin",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:00"
}, {
    "username": "joebloggs",
    "update": "19/07/2015 17:44:14"
}];

var result = _(data)
  .orderBy(v => {
    var ds = v.update.split(' ');
    ds[0] = ds[0].split('/').reverse().join('/');
    return new Date(ds.join(' '));
  }, 'desc')
  .uniqBy('username')
  .value();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdn.jsdelivr.net/lodash/4.12.0/lodash.min.js"></script>