JavaScript-如果至少2个具有相同的属性值,则合并数组的元素

我有一系列具有以下结构的对象:

days : string // "mo","tu","we"..
time : string // "9am - 3pm"

当我有2个(或更多)具有相同天数的对象时,有时会发生.在这种情况下,我需要合并这些项目(更改时间值,从“相同”项目中合并值)

var array = [{
  days: "mo,tu,we,th",
  time: "9am - 3pm"
}, {
  days: "mo,tu,we,th",
  time: "5pm - 9pm"
}, {
  days: "sa,su",
  time: "9am - 2pm"
}];

var newArr = [];
for (var i = 0; i < array.length; i++) {
  var currItem = array[i];
  
  var mergedArray = [];
  array.forEach(function(el) {
    if (currItem.days == el.days) {
      mergedArray.push(el.time);
    }
  });
  var mergedTime =  mergedArray.join(', ');
  currItem.time = mergedTime;
  if (newArr.filter(function(item) {
    return item.days == currItem.days;
  }).length < 1) {
    newArr.push(currItem);
  }
}

console.log(newArr);

这就是我所看到的,如何合并数组项的方法,但是由于内部有很多循环,我不喜欢它.还有更优雅的解决方案吗?也许使用lodash.

解决方法:

您可以使用_.uniqWith并篡改对象引用来获得预期的结果.

如果您不想修改原始数组,可以将数组的_ .cloneDeep传递给_.uniqWith函数.

var arr = [{
  days: "mo,tu,we,th",
  time: "9am - 3pm"
}, {
  days: "mo,tu,we,th",
  time: "5pm - 9pm"
}, {
  days: "sa,su",
  time: "9am - 2pm"
}];

console.log(_.uniqWith(arr, function(a, b) {
  if (a.days === b.days) {
    b.time += ', ' + a.time;
    return true;
  }
}));
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
上一篇:相当于Java的lodash _.includes


下一篇:Lodash-一个一致性、模块化、高性能的 JavaScript 实用工具库介绍