使用 JavaScript 或下划线组合内部对象的值

Combine values of inner object using JavaScript or Underscore

我有一个数组如下:

const arr = [{
  name: 'XYZ',
  values: [1, 2, 3]
}, {
  name: 'ABC',
  values: [5]
}, {
  name: 'XYZ',
  values: [4, 5, 6]
}, {
  name: 'ABC',
  values: [8, 9]
}];

我正在使用underscore js并尝试如下转换:

const result = [{
  name: 'XYZ',
  values: [1, 2, 3, 4, 5, 6]
}, {
  name: 'ABC',
  values: [5, 8, 9]
}]

我能够按 name 分组并尝试循环,但不确定如何合并 values。到目前为止,这就是我所做的:

_.chain(arr)
  .groupBy((item) => item.name)
  // I don't know what to do here
  .value();

使用 ES6,您可以使用 Array#reduce with a Map 来获得想要的结果:

const arr = [{"name":"XYZ","values":[1,2,3]},{"name":"ABC","values":[5]},{"name":"XYZ","values":[4,5,6]},{"name":"ABC","values":[8,9]}];

const result = [...arr.reduce((m, { name, values }) => {
  const el = m.get(name) || { name, values: [] }; // get the result object from the map or create a new one
  
  el.values.push(...values); // push the current values to the result object values property

  return m.set(name, el); // add the result object to the map, and return the map
}, new Map()).values()]; // get the map values, and spread to an array

console.log(result);

使用下划线:

const arr = [{"name":"XYZ","values":[1,2,3]},{"name":"ABC","values":[5]},{"name":"XYZ","values":[4,5,6]},{"name":"ABC","values":[8,9]}];

const result = _.chain(arr)
  .groupBy('name') // group by name
  .mapObject((group, name) => ({ // map each group to a new object
    name,
    values: _.flatten(_.pluck(group, 'values')) // get all values arrays, and flatten to a single array
  }))
  .values() // convert the groups object to an array
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

也许,你可以试试普通的Javascript方式。

var result = [];
arr.forEach((item) => {
    let currObj = result.find((item2) => item2.name === item.name);
    if(currObj){
      currObj.values = currObj.values.concat(item.values);
    } else {
      result.push(JSON.parse(JSON.stringify(item)));
    }
})