【发布时间】:2020-01-23 19:32:42
【问题描述】:
我有一个锯齿状数组,其中一系列列名包含在数组的第一行中,数据包含在后续行中。我需要将其转换为一个 Json 字符串,其中包含一系列具有从第一行中提取的属性名称的对象。
例如,如果我有:
var arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];
我需要结束:
[
{
"Age": "24",
"Class": "C",
"Group": "Prod"
},
{
"Age": "25",
"Class": "A",
"Group": "Dev"
},
{
"Age": "26",
"Class": "B",
"Group": "Test"
}
]
我已经编写了一些代码来做到这一点:
var arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];
var headings = arr[0]; /* Headings always contained in the first row*/
arr.shift(); /* Remove the first row of the array */
/* Create JSON string by iterating through each nested array and each of their respective values */
var jason = "[";
arr.forEach(function (x, y) {
jason += "{";
x.forEach(function (i, j) {
jason += "\"" + headings[j] + "\":\"" + i + "\"";
if (j < (x.length - 1)) {
jason += ",";
}
})
jason += "}";
if (y < (x.length - 1)) {
jason += ",";
}
});
jason += "]";
console.log(jason);
我正在尝试创建一个更大的数据集来测试它,但我希望比我更了解 javascript 的人可以帮助我确定是否有更有效的方法。
例如,我使用arr.forEach 遍历了锯齿状数组,而我本可以使用顺序 for 循环。我需要考虑任何性能问题吗?
我要注意的是,锯齿状数组中每个数组的长度总是相同的。 谢谢
【问题讨论】:
标签: javascript arrays json