有人知道一种方法(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'
        }
    ]
}

当前回答

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');

其他回答

您可以尝试在调用per iteration的函数中修改对象_。groupBy func。 注意,源数组改变了它的元素!

var res = _.groupBy(cars,(car)=>{
    const makeValue=car.make;
    delete car.make;
    return makeValue;
})
console.log(res);
console.log(cars);

我用REAL GROUP BY作为JS数组的例子和这个任务完全一样

const inputArray = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ]; var outObject = inputArray.reduce(function(a, e) { // GROUP BY estimated key (estKey), well, may be a just plain key // a -- Accumulator result object // e -- sequentally checked Element, the Element that is tested just at this itaration // new grouping name may be calculated, but must be based on real value of real field let estKey = (e['Phase']); (a[estKey] ? a[estKey] : (a[estKey] = null || [])).push(e); return a; }, {}); console.log(outObject);

const groupBy = (array, callback) => {
  const groups = {};
  
  array.forEach((element) => {
    const groupName = callback(element);
    if (groupName in groups) {
      groups[groupName].push(element);
    } else {
      groups[groupName] = [element];
    }
  });
  
  return groups;
};

或者花哨的裤子:

(() => {
  Array.prototype.groupBy = function (callback) {
    const groups = {};
    this.forEach((element, ...args) => {
      const groupName = callback(element, ...args);
      if (groupName in groups) {
        groups[groupName].push(element);
      } else {
        groups[groupName] = [element];
      }
    });

    return groups;
  };
})();

const res = [{ name: 1 }, { name: 1 }, { name: 0 }].groupBy(({ name }) => name);

// const res = {
//   0: [{name: 0}],
//   1: [{name: 1}, {name: 1}]
// }

这是一个MDN阵列的填充。groupBy函数。

我喜欢写它没有依赖/复杂性,只是纯粹的简单js。

const mp = {} const cars = [ { model: 'Imaginary space craft SpaceX model', year: '2025' }, { 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' } ] cars.forEach(c => { if (!c.make) return // exit (maybe add them to a "no_make" category) if (!mp[c.make]) mp[c.make] = [{ model: c.model, year: c.year }] else mp[c.make].push({ model: c.model, year: c.year }) }) console.log(mp)

对于key可以为null的情况,我们希望将它们分组为其他

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'},
            {'make':'kia','model':'optima','year':'2033'},
            {'make':null,'model':'zen','year':'2012'},
            {'make':null,'model':'blue','year':'2017'},

           ];


 result = cars.reduce(function (r, a) {
        key = a.make || 'others';
        r[key] = r[key] || [];
        r[key].push(a);
        return r;
    }, Object.create(null));