演示
使用您提供的数据:
var data = [
["fruits","frozen","fresh","rotten"],
["apples",884,494,494],
["oranges",4848,494,4949],
["kiwi",848,33,33]
]
以下函数将数组的第一个元素视为对象属性的键。然后它将遍历剩余的元素,并使用这些键将它们转换为对象。最后,它将返回这些新对象的数组。
function convertToArrayOfObjects(data) {
var keys = data.shift(),
i = 0, k = 0,
obj = null,
output = [];
for (i = 0; i < data.length; i++) {
obj = {};
for (k = 0; k < keys.length; k++) {
obj[keys[k]] = data[i][k];
}
output.push(obj);
}
return output;
}
输出
[
{ fruits: 'apples', fresh: 494, frozen: 884, rotten: 494 },
{ fruits: 'oranges', fresh: 494, frozen: 4848, rotten: 4949 },
{ fruits: 'kiwi', fresh: 33, frozen: 848, rotten: 33 }
]