0

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"} ] 

    2 Answers 2

    1

    here is simple demo.

    var arrayOfArrays = [ ["Name", "Age", "Address"], ["A", "43", "CA"], ["B", "23", "VA"], ["C", "24", "NY"] ]; function testConvert(arr) { var result = []; var keys = arr[0]; for (var i = 1; i < arr.length; i++) { var item = {}; item[keys[0]] = arr[i][0]; item[keys[1]] = arr[i][1]; item[keys[2]] = arr[i][2]; result.push(item); } return result; } console.log(testConvert(arrayOfArrays));

      0

      Extract the headers and use the map function:

      var headers = arrayOfArrays.splice(0,1)[0]; var arrayOfObjects = arrayOfArrays.map(function(e) { var o = {}; headers.forEach(function(h, index) { o[h] = e[index]; }) return o; }); 

      Link HERE.

      1
      • How to make it dynamic? @AlonSegal
        – appy
        CommentedMar 20, 2017 at 13:51

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.