简体   繁体   English

如何将 Json 文件的格式转换为另一种格式?

[英]How to convert a Json files' format to another format?

I need to covert the following JSON files' format to the format that I given below.我需要将以下 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"]
}

to

  { 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" }

One possible solution is to use two nested for loops.一种可能的解决方案是使用两个嵌套的for循环。 You can use a for ... in loop to traverse the main input object, and a standard for statement to traverse the arrays stored inside the object.您可以使用for ... in循环遍历主输入对象,使用标准for 语句遍历存储在对象内部的数组。

 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;}

You could take an object and take the keys as key and the values of the arrays as value, grouped by the same index.您可以将一个对象作为键,将数组的值作为值,按相同的索引分组。

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM