javascript:使用第一个“行"将二维数组转换为对象数组以定义属性 [英] javascript: convert two dimensional array to array of objects using the first 'row' to define properties
本文介绍了javascript:使用第一个“行"将二维数组转换为对象数组以定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了填充接收行对象数组的数据网格, 我正在寻找一种转换这样的数组的好方法:
In order to populate a data-grid that receives array of row objects, I am looking for a good solution to convert an array such as this:
[
['country', 'population'],
['someplace', 100],
['otherplace', 200]
]
放入这样的对象数组:
[
{country: 'someplace', population: 100},
{country: 'otherplace', population: 200},
]
更新:
这是我到目前为止使用的解决方案:
this is the solution I am using so far:
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;
}
推荐答案
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;
}, {});
});
这篇关于javascript:使用第一个“行"将二维数组转换为对象数组以定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文