Extracting matched items from an object which has properties of arrays I have a data object like that:

const data = {
  "id": ["1", "2", "3"],
  "name": ["foo", "bar", "baz"],
  "age": [20, 30, 40 ],
  "location": ["pluto", "mars", "jupiter"],
};


Those properties are matched in the array order. I need to create an array which holds all the items like:

[ 
  { id: '1', name: 'foo', age: 20, location: 'pluto' },
  { id: '2', name: 'bar', age: 30, location: 'mars' },
  { id: '3', name: 'baz', age: 40, location: 'jupiter' }
]


I tried many things including reduce but can't get a decent way of doing this. Here is how I'm creating this result:

let item = {};
let items = [];
const length = Object.values( data)[0].length;


for( i = 0; i &lt; length; i++) {
  Object.entries( data ).forEach( ( [key,value] ) =&gt;
      item = { ...item, [key]: value[i] }
  );

  items = [ ...items, item ];
}


But, the way that I am getting the length, using a for loop really bothers me.
Try this code:

function transformObject(data) {
  const values = Object.values(data);
  const keys = Object.keys(data);
  const transposed = values[0].map((col, i) =&gt; values.map(row =&gt; row[i]));
  return transposed.map(itemArr =&gt; keys.reduce((acc, key, i) =&gt; ({...acc, [key]: itemArr[i]}), {}));
}


The idea is to transpose the values 2D array and then map it using reduce for each row. The transposed array will look like:

[
  ["1", "foo", 20, "pluto"],
  ["2", "bar", 30, "mars"],
  ...
]


This piece of code keys.reduce((acc, key, i) =&gt; ({...acc, [key]: itemArr[i]}), {}) is simply zips two arrays: keys and the row from transposed array.



function transformObject(data) {
  const values = Object.values(data);
  const keys = Object.keys(data);
  const transposed = values[0].map((col, i) =&gt; values.map(row =&gt; row[i]));
  return transposed.map(itemArr =&gt; keys.reduce((acc, key, i) =&gt; ({...acc, [key]: itemArr[i]}), {}));
}

console.log(transformObject({
  "id": ["1", "2", "3"],
  "name": ["foo", "bar", "baz"],
  "age": [20, 30, 40 ],
  "location": ["pluto", "mars", "jupiter"],
}));