Dana Chen Dana Chen - 17 days ago 5
Javascript Question

How to convert an object of parallel lists to a list of objects?

I've got an object like

var data = [
{
"Name": ["Jane", "Peter", "Jenny"],
"Id": [1, 2, 3],
"Years": [16, 17, 18]
}
];


But I want to put it to a react table which need another format like it

var data1 = [
{
"Name": "Jane",
"Id": 1,
"Years": 16,
},
{
"Name": "Peter",
"Id": 2,
"Years": 17,
},
{
"Name": "Jenny",
"Id": 3,
"Years": 18,
}
]


How can I conversion it with JSX?

Answer

I'd find out the maximum property length (in case they aren't all the same), create an array of that size, iterate in a for-loop, create objects using the data keys and matching index positions (null if there's no match) and push them into the array.

const data = [{
  "Name": ["Jane", "Peter", "Jenny"],
  "Id": [1, 2, 3],
  "Years": [16, 17, 18]
}]

const interestingData = data[0]
const keys = Object.keys(interestingData)

const maxItems = keys.reduce((count, key) => Math.max(count, interestingData[key].length), 0)

const transformed = new Array(maxItems)
for (var i = 0; i < maxItems; i++) {
  transformed[i] = keys.reduce((obj, key) => Object.assign(obj, {
    [key]: interestingData[key][i] || null // default value if no matching index
  }), Object.create(null))
}

console.info(transformed)