gpt4 book ai didi

javascript - javascript中的数据转换

转载 作者:行者123 更新时间:2023-12-03 23:19:56 24 4
gpt4 key购买 nike

我将以下类型的数据分配给 var dataTransformation ,我使用度量标准从 apache 超集中的用户那里获取。

{country: "Afghanistan", region: "South Asia", year: 1960, value: 91.779}
{country: "Afghanistan", region: "South Asia", year: 1961, value: 91.492}
{country: "Afghanistan", region: "South Asia", year: 1962, value: 91.195}
{country: "Bangladesh", region: "South Asia", year: 1960, value: 94.865}
{country: "Bangladesh", region: "South Asia", year: 1961, value: 94.722}
{country: "Bangladesh", region: "South Asia", year: 1962, value: 94.502}
{country: "Canada", region: "North America", year: 1960, value: 30.939}
{country: "Canada", region: "North America", year: 1961, value: 30.332}
{country: "Canada", region: "North America", year: 1962, value: 29.506}
但我想将其转换为以下格式。我尝试使用数组映射函数、循环和字符串连接,但效率不高。有没有办法在javascript中做到这一点?
{
"South Asia": [
["Afghanistan", 91.779, 91.492, 91.195],
["Bangladesh", 94.865, 94.722, 94.502],
],
"North America":[
["Canada", 30.939, 30.332, 29.506],
],
}
我期待一个关于如何做到这一点的指南,而不是完全工作的代码。

最佳答案

const data = [{
country: "Afghanistan",
region: "South Asia",
year: 1960,
value: 91.779
},{
country: "Afghanistan",
region: "South Asia",
year: 1961,
value: 91.492
},{
country: "Afghanistan",
region: "South Asia",
year: 1962,
value: 91.195
},{
country: "Bangladesh",
region: "South Asia",
year: 1960,
value: 94.865
},{
country: "Bangladesh",
region: "South Asia",
year: 1961,
value: 94.722
},{
country: "Bangladesh",
region: "South Asia",
year: 1962,
value: 94.502
},{
country: "Canada",
region: "North America",
year: 1960,
value: 30.939
},{
country: "Canada",
region: "North America",
year: 1961,
value: 30.332
},{
country: "Canada",
region: "North America",
year: 1962,
value: 29.506
}];

const res = data.reduce((acc, {country, region, year, value}) => {
acc = {
...acc,
[region]: {
...acc[region],
[country]: !acc?.[region]?.[country] ? [value] : acc[region][country].concat(value)
}
}
return acc;
}, { });

console.log(res);

关于javascript - javascript中的数据转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66346512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com