gpt4 book ai didi

javascript - 转换对象数组的结构

转载 作者:行者123 更新时间:2023-11-30 09:44:47 24 4
gpt4 key购买 nike

我有这样的数据-

var data = [{"DefaultZone":[{"key":"stream0","value":100},
{"key":"stream1","value":50},
{"key":"stream2","value":10}
]},
{"Zone 1":[{"key":"stream0","value":120},
{"key":"stream1","value":55},
{"key":"stream2","value":15}
]}
]

并想将其改造为 -

var data = [{"key": "stream0", "values":[{"x":"DefaultZone","y":100}, {"x":"Zone 1","y":120}]},
{"key": "stream1", "values":[{"x":"DefaultZone","y":50}, {"x":"Zone 1","y":55}]},
{"key": "stream2", "values":[{"x":"DefaultZone","y":10}, {"x":"Zone 1","y":15}]}
];

使用 JavaScript(ES6)。任何帮助将不胜感激..

最佳答案

这是我想到的第一种方式:

var data = [{
"DefaultZone": [
{ "key": "stream0", "value": 100 },
{ "key": "stream1", "value": 50 },
{ "key": "stream2", "value": 10 }]
}, {
"Zone 1": [
{ "key": "stream0", "value": 120 },
{ "key": "stream1", "value": 55 },
{ "key": "stream2", "value": 15 }]
}];

let working = data.reduce((p, c) => {
let x = Object.keys(c)[0];
c[x].forEach(v => {
if (!p[v.key]) p[v.key] = [];
p[v.key].push({ x: x, y: v.value });
});
return p;
}, {});

let output = Object.keys(working).map(v => ({ key: v, values: working[v] }));

console.log(output);

进一步阅读:

关于javascript - 转换对象数组的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39323166/

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