我需要将以下JSON文件的格式转换为我在下面给出的格式。
{
"rank":["1","2","3","4","5"],
"user":["DanSPT","Tommer","Adam","Ben","Reed"],
"speed":["180kmh", "200kmh", "190kmh" ,"230kmh" ,"300kmh"],
"awards":["520", "314" ,"236", "212" ,"201"],
"carColor":["Red", "Blue", "Green", "Yellow", "Pink"]
}
到
{ rank: "1", user: "DanSPT", speed: "180kmh", awards: " 520 ", carColor: "Red" },
{ rank: "2", user: "Tommer", speed: "200kmh", awards: " 314 ", carColor: "Blue" },
{ rank: "3", user: "Adam", speed: "190kmh", awards: " 236 ", carColor: "Green" },
{ rank: "4", user: "Ben", speed: "230kmh", awards: " 212 ", carColor:"Yellow" },
{ rank: "5", user: "Reed", speed: "300kmh", awards: " 201 ", carColor:"Pink" }
答案 0 :(得分:0)
您可以使用一个对象,并将键作为键,并将数组的值作为值,并按相同的索引分组。
var data = { rank: ["1", "2", "3", "4", "5"], user: ["DanSPT", "Tommer", "Adam", "Ben", "Reed"], speed: ["180kmh", "200kmh", "190kmh", "230kmh", "300kmh"], awards: ["520", "314", "236", "212", "201"], carColor: ["Red", "Blue", "Green", "Yellow", "Pink"] },
result = Object
.entries(data)
.reduce((r, [k, a]) => a.map((v, i) => Object.assign(r[i] || {}, { [k]: v })), []);
console.log(result);
答案 1 :(得分:0)
一种可能的解决方案是使用两个嵌套的for
循环。您可以使用for ... in循环遍历主输入对象,并使用标准for statement遍历存储在对象内部的数组。
const input = {
"rank": ["1", "2", "3", "4", "5"],
"user": ["DanSPT", "Tommer", "Adam", "Ben", "Reed"],
"speed": ["180kmh", "200kmh", "190kmh" ,"230kmh" ,"300kmh"],
"awards": ["520", "314" ,"236", "212" ,"201"],
"carColor": ["Red", "Blue", "Green", "Yellow", "Pink"]
};
const output = [];
for (const key in input)
{
// Continue to next iteration if key don't hold an array.
if (!Array.isArray(input[key]))
continue;
// Store the array data on the "output".
for (let i = 0; i < input[key].length; i++)
{
output[i] = output[i] || {};
output[i][key] = input[key][i];
}
}
console.log(output);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}