Home > front end >  creating array of objects from an array of arrays
creating array of objects from an array of arrays

Time:11-19

I have this array

[
  [ [ 'id', 'name' ], [ '1', 'A' ] ],
  [ [ 'id', 'name' ], [ '2', 'B' ] ],
  [ [ 'id', 'name' ], [ '3', 'C' ] ]
] 

and i want it to be array of object with the corresponding value

[{id: 1, name: 'A'}, {id:2, name: 'B'}, {id:3, name: 'C'}]

thank you

CodePudding user response:

You can use any higher-order functions in js like map, for, reduce. Below is the implementation with Array.reduce

const arr = [
 [
   ['id', 'name'],
   ['1', 'A'],
 ],
 [
   ['id', 'name'],
   ['2', 'B'],
 ],
 [
   ['id', 'name'],
   ['3', 'C'],],
 ];


const response = arr.reduce((acc, curr) => {
   const [firstItem, secondItem] = curr;
   const [id, name] = firstItem;
   const [val1, val2] = secondItem;
   acc.push({ [id]: val1, [name]: val2 });
   return ACC;
}, []);

console.log(response)

CodePudding user response:

You could transpose the inner arrays and map new objects.

const
    transpose = (a, b) => b.map((v, i) => [...(a[i] || []), v]),
    data = [[['id', 'name'], ['1', 'A'] ], [['id', 'name'], ['2', 'B']], [['id', 'name'], ['3', 'C']]],
    result = data.map(a => Object.fromEntries(a.reduce(transpose, [])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using Array#map iterate over the array.

For every subarray, it will have a list of keys and a list of values. Using Array#reduce, you can iterate over keys to compute an object with the help of the third parameter, the index, to get each corresponding value:

const data = [
  [ [ 'id', 'name', 'age' ], [ '1', 'A', 22 ] ],
  [ [ 'id', 'name' ], [ '2', 'B' ] ],
  [ [ 'id', 'name' ], [ '3', 'C' ] ]
];

const arr = data.map(([ keys, values = [] ]) => 
  keys.reduce((obj, key, i) => ({ ...obj, [key]: values[i] }), {})
);

console.log(arr);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related