有一个条件,我需要将对象数组转换为数组数组



有一个条件,我需要将对象数组转换为数组数组。 下面给出了一个数组,因为数据将此数组转换为格式化数组。

data = [
{
"total": 1,
"third": 0,
"city": "Agra",
"first": 0,
"second": 0
},
{
"total": 2,
"third": 0,
"city": "Agra",
"first": 0,
"second": 0
},
{
"total": 3,
"third": 0,
"city": "Delhi",
"first": 0,
"second": 0
},
{
"total": 4,
"third": 0,
"city": "Delhi",
"first": 0,
"second": 0
}
]

如何将上面的对象数组转换为下面的数组数组?

formatedArray=[
"Agra":[
{
"total": 1,
"third": 0,
"city": "Agra",
"first": 0,
"second": 0
},
{
"total": 2,
"third": 0,
"city": "Agra",
"first": 0,
"second": 0
}
],
"Delhi":[
{
"total": 4,
"third": 0,
"city": "Delhi",
"first": 0,
"second": 0
},
{
"total": 4,
"third": 0,
"city": "Delhi",
"first": 0,
"second": 0
}
]
]

你可以通过vanilla JavaScript来完成。可以使用的方法reduce()方法:

const data = [
{
"total": 1,
"third": 0,
"city": "Agra",
"first": 0,
"second": 0
},
{
"total": 2,
"third": 0,
"city": "Agra",
"first": 0,
"second": 0
},
{
"total": 3,
"third": 0,
"city": "Delhi",
"first": 0,
"second": 0
},
{
"total": 4,
"third": 0,
"city": "Delhi",
"first": 0,
"second": 0
}
];

代码如下所示:

const desired = data.reduce((acc, currentValue) => {
acc[currentValue.city] = acc[currentValue.city] || [];        
acc[currentValue.city].push(currentValue);    
return acc;
}, {})
console.log(desired);

我建议你看看lodash groupby函数:

https://lodash.com/docs/4.17.15#groupBy

formatedArray = _.groupBy(data, obj => obj.city);

这是一个基于角度的快速堆叠闪电战示例

https://stackblitz.com/edit/angular-dpj8jh

最新更新