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

当前回答

对于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));

其他回答

这是一个通用函数,将返回Array groupBy自己的键。

const getSectionListGroupedByKey = < T > ( property: keyof T, List: Array < T > ): Array < { title: T[keyof T];data: Array < T > } > => { const sectionList: Array < { title: T[keyof T];data: Array < T > } > = []; if (!property || !List ? .[0] ? .[property]) { return []; } const groupedTxnListMap: Map < T[keyof T], Array < T >> = List.reduce((acc, cv) => { const keyValue: T[keyof T] = cv[property]; if (acc.has(keyValue)) { acc.get(keyValue) ? .push(cv); } else { acc.set(keyValue, [cv]); } return acc; }, new Map < T[keyof T], Array < T >> ()); groupedTxnListMap.forEach((value, key) => { sectionList.push({ title: key, data: value }); }); return sectionList; }; // Example 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' }, ]; const result = getSectionListGroupedByKey('make', cars); console.log('result: ', result)

Var汽车= [{ :“奥迪”, 模型:“r8”, :“2012” },{ :“奥迪”, 模型:“生活费”, :“2013” },{ :“福特”, 模型:“野马”, :“2012” },{ :“福特”, 模型:“融合”, :“2015” },{ :“克钦独立军”, 模型:“最佳状态”, :“2012” })。Reduce ((r, car) => { const { 模型中, 一年, 使 } =汽车; R [make] =[…]R [make] || [], { 模型中, 一年 }); 返回r; }, {}); console.log(汽车);

Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.

Array.prototype.groupBy = function(k) {
  return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
};

const projs = [
  {
    project: "A",
    timeTake: 2,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 4,
    desc: "this is a description"
  },
  {
    project: "A",
    timeTake: 12,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 45,
    desc: "this is a description"
  }
];

console.log(projs.groupBy("project"));

下面是一个受到Java中的collections . groupingby()启发的解决方案:

function groupingBy(list, keyMapper) { 返回列表。reduce((accummalatorMap, currentValue) => { const key = keyMapper(currentValue); 如果(! accummalatorMap.has(键)){ accummalatorMap。集(关键,[currentValue]); }其他{ accummalatorMap。集(键,accummalatorMap.get(关键).push (currentValue)); } 返回accummalatorMap; }, new Map()); }

这将给出一个Map对象。

/ /使用 const cars = groupingBy(cars, car => car.make);

您正在寻找_.groupBy()。

如果需要,从对象中删除分组的属性应该很简单:

Const cars = [{ “做”:“奥迪”, “模型”:“r8”, “年”:“2012” },{ “做”:“奥迪”, “模型”:“生活费”, “年”:“2013” },{ “做”:“福特”, “模型”:“野马”, “年”:“2012” },{ “做”:“福特”, “模型”:“融合”, “年”:“2015” },{ “做”:“克钦独立军”, “模型”:“最佳状态”, “年”:“2012” }); Const分组= _。groupBy(cars, car => car.make); console.log(分组); < script src = " https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js " > < /脚本>