有效地从 javascript 中的锯齿状数组创建 JSON 字符串

use*_*559 3 javascript arrays json

I have a jagged array where the series of column names is contained in the first row of the array and the data is contained in subsequent rows. I need to convert this into a Json string containing a series of objects with property names extracted from the first row.

例如,如果我有:

var arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];
Run Code Online (Sandbox Code Playgroud)

我需要结束:

[
  {
    "Age": "24",
    "Class": "C",
    "Group": "Prod"
  },
  {
    "Age": "25",
    "Class": "A",
    "Group": "Dev"
  },
  {
    "Age": "26",
    "Class": "B",
    "Group": "Test"
  }
]
Run Code Online (Sandbox Code Playgroud)

我已经写了一些代码来做到这一点:

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);
Run Code Online (Sandbox Code Playgroud)

I am trying to create a bigger dataset to test it on but I was hoping someone who knows a bit more about javascript than I do could help me determine if there is a more efficient way to do it.

例如,我已经使用 arr.forEach whereas I could have used a sequential for loop. Are there any performance concerns that I need to consider?

我应该注意到锯齿状数组中每个数组的长度总是相同的。谢谢

Kob*_*obe 5

您可以使用map并排reduce

我们知道 的第一个元素arr是键,所以我们可以把shift它弄出来,然后是map每个其他元素,然后将reduce它们变成对象:

const arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];

const keys = arr.shift()

const out = arr.map(arr => arr.reduce((a, el, i) => (a[keys[i]] = el, a), {}))
console.log(out)
Run Code Online (Sandbox Code Playgroud)