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



我的数组如下:

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

我正在使用下划线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#用映射降低来获得所需的结果:

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>

也许,您可以尝试Vanilla 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)));
    }
})

最新更新