How to convert nested array pairs to objects in an array in JavaScript ?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of arrays like this −

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

We are required to write a JavaScript function that takes in one such array. The function should construct an array of objects based on this array of arrays.

The output array should contain an object for each unique user and other details about it.

Therefore, the output for the array should look like −

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

Example

The code for this will be −

const arr = [
   [
      ['firstName', 'Joe'],
      ['lastName', 'Blow'],
      ['age', 42],
      ['role', 'clerk'],
      [
         ['firstName', 'Mary'],
         ['lastName', 'Jenkins'],
         ['age', 36],
         ['role', 'manager']
      ]
   ]
];
const convertToObject = (arr = []) => {
   const empty = {};
   const res = arr.map(el => {
      const object = this;
      el.forEach(attr => {
         let name = attr[0], value = attr[1];
         object[name] = value;
         return object;
      }, object);
      return this;
   }, empty);
   return res;
}
console.log(convertToObject(arr));

Output

And the output in the console will be −

[
   {
      firstName: 'Joe',
      lastName: 'Blow',
      age: 42,
      role: 'clerk',
      'firstName,Mary': [ 'lastName', 'Jenkins' ]
   }
]
raja
Published on 24-Nov-2020 09:47:13
Advertisements