为D3平坦数组



我正在从mongoDB导入数据,我正在使用javascript和React。我需要为D3.js平展数组。

我:

[{
"location": [ { "createdAt": "2023-04-03T18:27:42.088Z" } ],
"count": 2,
"item": [ { "name": "football" } ]
},{
"location": [ { "createdAt": "2023-04-03T18:27:42.088Z" } ],
"count": 1,
"item": [ { "name": "Baseball" } ]
}]

但是想:

[{
"createdAt": "2023-04-03T18:27:42.088Z",
"count": 2,
"name": "football" 
},{
"createdAt": "2023-04-03T18:27:42.088Z" ,
"count": 1,
"name": "baseball"
}]

我尝试遍历对象,但得到:

{
0.item.0.name:  "baseball"
0.count: 1
0.location.0.createdAt: "2023-04-03T18:27:42.088Z"
1.etc...
}

我也试过:console.log(array.flatMap((element) => element).flat()) ;

但这没有任何作用

您可以使用map和解构:

const data = [
{
"location": [{ "createdAt": "2023-04-03T18:27:42.088Z" }],
"count": 2,
"item": [{ "name": "football" }]
},
{
"location": [{ "createdAt": "2023-04-03T18:27:42.088Z" }],
"count": 1,
"item": [{ "name": "Baseball" }]
}
];
const flattened = data.map(({ location: [{ createdAt }], count, item: [{ name }] }) => ({
createdAt,
count,
name
}));
console.log(flattened);

相关内容

  • 没有找到相关文章

最新更新