javascript:使用第一个'row'将二维数组转换为对象数组以定义属性

Cod*_*oad 2 javascript arrays

为了填充接收行对象数组的数据网格,我正在寻找一个很好的解决方案来转换这样的数组:

[  
['country', 'population'],
['someplace', 100],
['otherplace', 200]
]
Run Code Online (Sandbox Code Playgroud)

进入一个对象数组,如下所示:

[
{country: 'someplace', population: 100},
{country: 'otherplace', population: 200},
]
Run Code Online (Sandbox Code Playgroud)

更新:

这是我到目前为止使用的解决方案:

 function arrayToRows(arr) {
var defs = [];
var data = [];
var rows = [];
var r;
var obj;



var headerRow = arr.shift(); //remove header row

defs = headerRow.map(function(cell) {
  return {
    field: cell,
    displayName: cell
  }
});


for (var i = 0; i < arr.length; i++) {
  r = arr[i];
  obj = {};

  for (var j = 0; j < defs.length; j++) {
    obj[defs[j].field] = r[j];
  }
  rows.push(obj);
}
return rows;
Run Code Online (Sandbox Code Playgroud)

}

Ber*_*rgi 11

var array = [  
    ['country', 'population'],
    ['someplace', 100],
    ['otherplace', 200]
];

var keys = array.shift();
var objects = array.map(function(values) {
    return keys.reduce(function(o, k, i) {
        o[k] = values[i];
        return o;
    }, {});
});
Run Code Online (Sandbox Code Playgroud)