我得到一个对象数组:
const inputStructure = [
{
state: 'LA',
insurance: 'Test1'
},
{
state: 'LA',
insurance: 'Test2'
},
{
state: 'TX',
insurance: 'Test3'
}
]
如何将具有相同state
属性的对象分组?我需要创建一个返回以下结果的函数:
const outputStructure = {
'LA': {
state: 'LA',
insurances: ['Test1', 'Test2']
},
'TX': {
state: 'TX',
insurances: ['Test3']
}
}
您可以使用:
const inputStructure = [
{
state: 'LA',
insurance: 'Test1'
},
{
state: 'LA',
insurance: 'Test2'
},
{
state: 'TX',
insurance: 'Test3'
}
];
const data = {};
for (const item of inputStructure) {
if (!data[item.state]) {
data[item.state] = {
state: item.state,
insurances: []
}
}
data[item.state].insurances.push(item.insurance);
}
console.log(data);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句