如何对数组obj进行分组?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何对数组obj进行分组?相关的知识,希望对你有一定的参考价值。
我是数组obj分组的新手。我尝试了以下的方法,我相信我已经达到了目的,但是我缺少了一些东西,我不明白在哪里。
Doing:
const result = data.map(function(item) {
const ditem = dictionary.find(d => d.state == item.state);
if(ditem) {
return {
...item,
"lat": ditem.lat ,
"long": ditem.long
}
}
return item;
});
console.log(result);
const formatted = result.map(area => {
return {
"state": area["state"],
"lat": area["lat"],
"long": area["long"],
"datasets": Object.keys(area)
.map(date => ({ date: area[date], negative: area[date]}))
};
});
给我:
[
{
"state": "AK",
"lat": "9875.33.00",
"long": "-8371.42.00",
"datasets": [
{
"date": 20200421,
"negative": 20200421
},
{
"date": "AK",
"negative": "AK"
},
{
"date": 329,
"negative": 329
},
{
"date": 10790,
"negative": 10790...
期待的例子:
0:
State: "AK",
Lat: 45.0732745
Long: 7.680687483
0: date: "2/24/20"
positive: 329
negative: 10790
pending: null
hospitalizedCurrently: 42
hospitalizedCumulative: 36...
1:
date: "2/25/20",
positive: 329
negative: 10790
pending: null
hospitalizedCurrently: 42
hospitalizedCumulative: 36...
答案
这可能是你要找的代码。
const formatted = Object.assign({},result.map(area => {
return {
"state": area["state"],
"lat": area["lat"],
"long": area["long"],
"datasets": Object.assign({},Object.keys(area)
.map(date => ({ date: area[date], negative: area[date]})))
};
}))
以上是关于如何对数组obj进行分组?的主要内容,如果未能解决你的问题,请参考以下文章