有人知道一种方法(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'
}
]
}
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' ] } ]
使用lodash/fp,你可以使用_.flow()创建一个函数,它首先按键分组,然后映射每个组,并从每个项中省略一个键:
const { flow, groupBy, mapValues, map, omit } = _;
const groupAndOmitBy = key => flow(
groupBy(key),
mapValues(map(omit(key)))
);
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 groupAndOmitMake = groupAndOmitBy('make');
const result = groupAndOmitMake(cars);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
提莫的答案是我会怎么做。简单的_。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。