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

当前回答

另一个解决方案:

Var汽车= [ {“使”:“奥迪”,“模型”:“r8”,“年”:“2012”},{“使”:“奥迪”,“模型”:“生活费”,“年”:“2013”}, {“使”:“福特”,“模型”:“野马”,“年”:“2012”},{“使”:“福特”,“模型”:“融合”,“年”:“2015”}, {'make': 'kia','model': 'optima','year': '2012'}, ]; const reducedCars =汽车。Reduce ((acc, {make, model, year}) => ( { acc, [make]: acc[make] ?[…Acc [make], {model, year}]: [{model, year}], } ), {}); console.log (reducedCars);

其他回答

试试这个吧,我觉得挺好用的。

让分组= _。groupBy(汽车,“使”);

注意:使用lodash lib,所以包括它。

完全没有理由下载第三方库来解决这个简单的问题,就像上面的解决方案所建议的那样。

在es6中按特定键对对象列表进行分组的单行版本:

const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})

较长的版本过滤掉没有键的对象:

function groupByKey(array, key) { return array .reduce((hash, obj) => { if(obj[key] === undefined) return hash; return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}) }, {}) } 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'}]; console.log(groupByKey(cars, 'make'))

注意:原来的问题似乎是问如何按制造商对汽车进行分组,但省略了每组中的制造商。因此,如果没有第三方库,简单的回答是这样的:

const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {}) 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'}]; console.log(groupByKey(cars, 'make', {omitKey:true}))

letfinaldata=[]

let data =[{id:1,name:"meet"},{id:2,name:"raj"},{id:1,name:"hari"},{id:3,name:"hari"},{id:2,name:"ram"}]

data = data.map((item)=> 
{
    return {...item,
        name: [item.name]
    }
}) // Converting the name key from string to array


let temp = [];

for(let i =0 ;i<data.length;i++)
{
    const index = temp.indexOf(data[i].id) // Checking if the object id is already present
    if(index>=0)
    {
        letfinaldata[index].name = [...letfinaldata[index].name,...data[i].name] // If present then append the name to the name of that object
    }
    else{
        temp.push(data[i].id); // Push the checked object id
        letfinaldata.push({...data[i]}) // Push the object
    }
}

console.log(letfinaldata)

输出

[ { id: 1, name: [ 'meet', 'hari' ] },
  { id: 2, name: [ 'raj', 'ram' ] },
  { id: 3, name: [ 'hari' ] } ]

下面是您自己的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(结果);

这是一个通用函数,将返回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)