Skip to content Skip to sidebar Skip to footer

How To Convert Nested Array Pairs To Objects In An Array

I have been tasked to convert the following array to an array of object pairs: var arr = [ [ ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'cl

Solution 1:

Programmatic solution (available too at https://jsfiddle.net/edorka/jnLxyzhb/):

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

var empty = {};
var result = arr.map(function(objectArray){
    varobject = this;
    var attribute = objectArray.map(function(attrArray){
        var name = attrArray[0], value = attrArray[1];
        object[name] = value;
        returnobject;
    }, object);
    returnthis;
}, empty);

console.log(result);

Solution 2:

You can convert it like this -

var arr = [
            {'firstName':'Joe','lastName':'Blow','age':42,'role':'clert‌​'},
            {'firstName':'Mar‌​y','lastName':'Jenki‌​ns','age':36,'role':‌​'manager'}
          ]

Solution 3:

example of an array of objects

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

Solution 4:

You could use an iterative and recursive approach for the nested arrays.

var array = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk'], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]]],
    result = [];

array[0].forEach(functioniter(a, i) {
    i || result.push({});
    if (i < 4) {
        result[result.length - 1][a[0]] = a[1];
        return;
    }
    Array.isArray(a) && a.forEach(iter);
});
   
console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Solution 5:

functionconvert(array) {
  returnarray.map(function(person) {
    return person.reduce(function(obj, prop, index) {
      if (!obj[prop[0]]) {
        obj[prop[0]] = prop[1];
      }

      return obj;
    }, {});
  }); 
}
  • use the map function to select each "person" array
  • use the reduce function to convert each "person" array to an object
  • the map function will also return a new array of objects
  • the original array will not be altered

Post a Comment for "How To Convert Nested Array Pairs To Objects In An Array"