Search code examples
javascriptarraysjavascript-objects

How to convert array of arrays to array of objects where keys are taken from the first array?


I have a variable that is returning an array of arrays, with each item in each array in double quotes.

var arrayOfArrays = [
  [ "Name", "Age", "Address" ],
  [ "A", "43", "CA" ],
  [ "B", "23", "VA" ],
  [ "C", "24", "NY" ]
]

I need to convert this to the following:

var arrayOfObjects = [
  {"Name":"A", "Age":"43", "Address":"CA"},
  {"Name":"B", "Age":"23", "Address":"VA"},
  {"Name":"C", "Age":"24", "Address":"NY"}
]

Solution

  • Update

    Less verbose version using Array.prototype.reduce() with newer language constructs like destructuring and computed property names:

    const arrays = [
      ["Name", "Age", "Address"],
      ["A", "43", "CA"],
      ["B", "23", "VA"],
      ["C", "24", "NY"]
    ];
    
    const [keys, ...values] = arrays;
    const objects = values.map(array => array.reduce((a, v, i) => ({...a, [keys[i]]: v}), {}));
    
    console.log(JSON.stringify(objects));


    Original answer

    Using Array.prototype.slice(), Array.prototype.map() and Array.prototype.forEach():

    const arrays = [
      ["Name", "Age", "Address"],
      ["A", "43", "CA"],
      ["B", "23", "VA"],
      ["C", "24", "NY"]
    ];
    
    const keys = arrays[0];
    const values = arrays.slice(1);
    const objects = values.map(array => {
      const object = {};
    
      keys.forEach((key, i) => object[key] = array[i]);
      
      return object;
    });
    
    console.log(JSON.stringify(objects));