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

瘦欲@ 提交于 2019-12-24 01:32:31

问题


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

回答1:


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

let arrays = [
  ["Name", "Age", "Address"],
  ["A", "43", "CA"],
  ["B", "23", "VA"],
  ["C", "24", "NY"]
];

let keys = arrays[0];
let values = arrays.slice(1);
let objects = values.map(array => {
  let object = {};

  keys.forEach((key, i) => object[key] = array[i]);
  
  return object;
});

console.log(JSON.stringify(objects));



回答2:


Hope this helps

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

function changeToObject(arrayOfArrays){  
    for (var i = 1; i < arrayOfArrays.length; i++) {
        var json = {
            "Name" : "",
            "Age" : "",
            "Address" : ""
        }
        json.Name = arrayOfArrays[i][0];
        json.Age = arrayOfArrays[i][1];
        json.Address = arrayOfArrays[i][2];
        arrayOfObjects.push(json);  
    };
    console.log(arrayOfObjects)

}

changeToObject(arrayOfArrays);


来源:https://stackoverflow.com/questions/42895449/how-to-convert-array-of-arrays-to-array-of-objects-where-keys-are-taken-from-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!