Home > database >  Expanding arrays in object properties to an array of objects
Expanding arrays in object properties to an array of objects

Time:06-18

How am I able to convert the following object:

data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
}

into the following array of objects:

new_data = [
  {sp: 'A', jh: '1', oa: 27493},
  {sp: 'B', jh: '0', oa: 9837},
  {sp: 'C', jh: 'AB', oa: 3781}
]

CodePudding user response:

Assuming the arrays are all the same size, map one of them and reduce the keys using the current index.

const data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
};

let keys = Object.keys(data);
let new_data = data[keys[0]].map(( _, idx ) => keys.reduce((a, c) => ({ ...a, [c]: data[c][idx] }), {}));

console.log(new_data)
.as-console-wrapper { max-height: 100% !important; top: auto; }

CodePudding user response:

  1. You can use Object.entries to get all of the key-value pairs in the object.
  2. You can take the length of the values of the array for the first entry as the length of the output, assuming that all of the arrays in the object are of the same length.
  3. Then, you can map over all of the possible indexes and use Object.fromEntries to create an object with the keys from the original object and the value being the value at that index in the array for that key in the original object.

const data = {
  sp: [ 'A', 'B', 'C' ],
  jh: [ '1', '0', 'AB' ],
  oa: [ 27493, 9837, 3781 ]
}
let entries = Object.entries(data);
let res = entries[0][1].map((_, i)=>Object.fromEntries(
                              entries.map(([k, v])=>[k, v[i]])));
console.log(res);

  • Related