Transform data from a nested array to an object in JavaScript


Suppose, we have the following array of arrays −

const arr = [
   [
      ['dog', 'Harry'], ['age', 2]
   ],
   [
      ['dog', 'Roger'], ['age', 5]
   ]
];

We are required to write a JavaScript function that takes in one such nested array. The function should then prepare an object based on the array.

The object for the above array should look like −

const output = [
   {dog: 'Harry', age: 2},
   {dog: 'Roger', age: 5}
];

Example

The code for this will be −

const arr = [
   [
      ['dog', 'Harry'], ['age', 2]
   ],
   [
      ['dog', 'Roger'], ['age', 5]
   ]
];
const prepareObjectArray = (arr = []) => {
   const copy = arr.slice();
   copy.forEach((el, ind, array) => {
      el.forEach((element, index, subArray) => {
         subArray[element[0]] = element[1];
      });
      el.length = 0;
      array[ind] = Object.assign({}, array[ind]);
   });
   return copy;
};
console.log(prepareObjectArray(arr));

Output

And the output in the console will be −

[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]

Updated on: 24-Nov-2020

639 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements