Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn nested arrays into objects

I have been unable to figure out how to turn a nested array such as:

var array = [
    [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '[email protected]'], ['weight', 180], ['occupation', 'repo']],
    [['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '[email protected]'],
 ['weight', 200], ['occupation', 'enforcement']]
];

into an object such as

var array = [
    {firstName: 'Henry', codeName: 'Etta', email: '[email protected]', weight: 180, occupation: 'repo'},
    {firstName: 'Bruce', codeName: 'DK', email: '[email protected]', weight: 200, occupation: 'enforcement'}
];

Below is what I've come up with so far, but it is clearly not producing the results I need.

function arrIntoObject(array) {
  var obj = {};

  array.map(function(a) {
    a.map(function(e) {
      obj[e[0]] = e[1];  
    });
  });
  return obj;
}

This seems like a question that would have been asked by now, but after hours I haven't been able to find a similar question, so I would appreciate any help or guidance here. Thanks!

like image 321
S Q Avatar asked Mar 06 '26 03:03

S Q


2 Answers

You can use a combination of .map() with .reduce(), like so:

var array = [
    [['firstName', 'Henry'], ['codeName', 'Etta'], ['email', '[email protected]'], ['weight', 180], ['occupation', 'repo']],
    [['firstName', 'Bruce'], ['codeName', 'DK'], ['email', '[email protected]'],
 ['weight', 200], ['occupation', 'enforcement']]
];

var objs = array.map(function (arr) {
  return arr.reduce(function (res, curr) {
    var [key, value] = curr;
    res[key] = value;
    return res;
  }, {});
});

console.log(objs);
like image 96
mhodges Avatar answered Mar 08 '26 16:03

mhodges


You could just reduce the arrays into an object

var array = [
  [['firstName', 'Henry'],['codeName', 'Etta'],['email', '[email protected]'],['weight', 180],['occupation', 'repo']],
  [['firstName', 'Bruce'],['codeName', 'DK'],['email', '[email protected]'],['weight', 200],['occupation', 'enforcement']]
];

var obj = array.map( arr => arr.reduce( (acc, curr) => { 
    acc[ curr[0] ] = curr[1]; return acc;
}, {}));


console.log(obj)
.as-console-wrapper {top:0; max-height: 100%!important}
like image 36
adeneo Avatar answered Mar 08 '26 16:03

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!