【问题标题】:Creating a JSON string from a jagged array in javascript efficiently有效地从 JavaScript 中的锯齿状数组创建 JSON 字符串
【发布时间】: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


    【解决方案1】:

    您可以在reduce 旁边使用map

    我们知道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)

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多