有人知道一种方法(lodash如果可能的话)通过对象键分组对象数组,然后根据分组创建一个新的对象数组吗?例如,我有一个汽车对象数组:

const cars = [
    {
        'make': 'audi',
        'model': 'r8',
        'year': '2012'
    }, {
        'make': 'audi',
        'model': 'rs5',
        'year': '2013'
    }, {
        'make': 'ford',
        'model': 'mustang',
        'year': '2012'
    }, {
        'make': 'ford',
        'model': 'fusion',
        'year': '2015'
    }, {
        'make': 'kia',
        'model': 'optima',
        'year': '2012'
    },
];

我想创建一个新的汽车对象数组,由make分组:

const cars = {
    'audi': [
        {
            'model': 'r8',
            'year': '2012'
        }, {
            'model': 'rs5',
            'year': '2013'
        },
    ],

    'ford': [
        {
            'model': 'mustang',
            'year': '2012'
        }, {
            'model': 'fusion',
            'year': '2015'
        }
    ],

    'kia': [
        {
            'model': 'optima',
            'year': '2012'
        }
    ]
}

当前回答

下面是您自己的groupBy函数,它是来自https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore的代码的泛化

函数groupBy(xs, f) { 返回x。减少((r, v, i, a、k = f (v)) = > ((r [k] | | (r [k] = [])) .push (v), r), {}); } Const cars = [{make: 'audi',型号:'r8',年份:'2012'},{make: 'audi',型号:'rs5',年份:'2013'},{make: 'ford',型号:'mustang',年份:'2012'},{make: 'ford',型号:'fusion',年份:'2015'},{make: 'kia',型号:'optima',年份:'2012'}]; const result = groupBy(cars, (c) => c.make); console.log(结果);

其他回答

提莫的答案是我会怎么做。简单的_。groupBy,并允许在分组结构中的对象中有一些重复。

然而,OP还要求删除重复的make键。如果你想从头到尾:

var grouped = _.mapValues(_.groupBy(cars, 'make'),
                          clist => clist.map(car => _.omit(car, 'make')));

console.log(grouped);

收益率:

{ audi:
   [ { model: 'r8', year: '2012' },
     { model: 'rs5', year: '2013' } ],
  ford:
   [ { model: 'mustang', year: '2012' },
     { model: 'fusion', year: '2015' } ],
  kia: 
   [ { model: 'optima', year: '2012' } ] 
}

如果你想使用Underscore.js来实现这个功能,请注意它的_. js版本。mapValues被称为_.mapObject。

下面是您自己的groupBy函数,它是来自https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore的代码的泛化

函数groupBy(xs, f) { 返回x。减少((r, v, i, a、k = f (v)) = > ((r [k] | | (r [k] = [])) .push (v), r), {}); } Const cars = [{make: 'audi',型号:'r8',年份:'2012'},{make: 'audi',型号:'rs5',年份:'2013'},{make: 'ford',型号:'mustang',年份:'2012'},{make: 'ford',型号:'fusion',年份:'2015'},{make: 'kia',型号:'optima',年份:'2012'}]; const result = groupBy(cars, (c) => c.make); console.log(结果);

function groupBy(data, property) {
  return data.reduce((acc, obj) => {
    const key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}
groupBy(people, 'age');

创建一个可以重用的方法

Array.prototype.groupBy = function(prop) {
      return this.reduce(function(groups, item) {
        const val = item[prop]
        groups[val] = groups[val] || []
        groups[val].push(item)
        return groups
      }, {})
    };

下面你可以根据任何标准进行分组

const groupByMake = cars.groupBy('make');
        console.log(groupByMake);

var cars = [ { 'make': 'audi', 'model': 'r8', 'year': '2012' }, { 'make': 'audi', 'model': 'rs5', 'year': '2013' }, { 'make': 'ford', 'model': 'mustang', 'year': '2012' }, { 'make': 'ford', 'model': 'fusion', 'year': '2015' }, { 'make': 'kia', 'model': 'optima', 'year': '2012' }, ]; //re-usable method Array.prototype.groupBy = function(prop) { return this.reduce(function(groups, item) { const val = item[prop] groups[val] = groups[val] || [] groups[val].push(item) return groups }, {}) }; // initiate your groupBy. Notice the recordset Cars and the field Make.... const groupByMake = cars.groupBy('make'); console.log(groupByMake); //At this point we have objects. You can use Object.keys to return an array

你也可以像这样使用数组#forEach()方法:

const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }]; let newcars = {} cars.forEach(car => { newcars[car.make] ? // check if that array exists or not in newcars object newcars[car.make].push({model: car.model, year: car.year}) // just push : (newcars[car.make] = [], newcars[car.make].push({model: car.model, year: car.year})) // create a new array and push }) console.log(newcars);