简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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