代码之家  ›  专栏  ›  技术社区  ›  Vimalraj Selvam MIZ

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

  •  0
  • Vimalraj Selvam MIZ  · 技术社区  · 7 年前

    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();
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Ori Drori    7 年前

    Array#reduce 用一个 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>
        2
  •  0
  •   prabhatojha    7 年前

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