Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of 3 Dimensions to an Array of Objects

Been stuck on this for a while.

let employees = [
 [
  ['firstName', 'Joe'],
  ['lastName', 'Blow'],
  ['age', 42],
  ['role', 'clerk']
 ],
 [
  ['firstName', 'Mary'],
  ['lastName', 'Jenkins'],
  ['age', 36],
  ['role', 'manager']
 ]
]

To yield:

[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]

How do transform this exactly? I have tried triple nested for loops, map/reduce, and shift(), but I can't get it work transform exactly

like image 424
jhazelton1 Avatar asked Aug 26 '17 05:08

jhazelton1


1 Answers

Try this solution. Use Array#map to iterate over first level items. In the map function iterate over nested array items via Array#forEach and populate your object. Then from map return that object.

let employees = [
 [
  ['firstName', 'Joe'],
  ['lastName', 'Blow'],
  ['age', 42],
  ['role', 'clerk']
 ],
 [
  ['firstName', 'Mary'],
  ['lastName', 'Jenkins'],
  ['age', 36],
  ['role', 'manager']
 ]
];

const newEmp = employees.map(emp => {
   const obj = {};
   
   emp.forEach(([prop, value]) => obj[prop] = value);
   
   return obj;
});

console.log(newEmp);
like image 196
Suren Srapyan Avatar answered Oct 08 '22 14:10

Suren Srapyan