生成多级JSON javasacript

时间:2017-11-01 20:17:21

标签: javascript arrays json object

之前我从未使用过JSON,所以我不熟悉它的语法。

目前我有多个包含不同数据的数组。

我想创建一个JSON对象,它包含多个数组,每个数组包含多个数据。

我有一个对象数组,例如:

{parent_name: "Table 1", child_name: "Table 1.1", documentNo: "BEC32568/17"}

{parent_name: "Table 1", child_name: "Table 1.1", documentNo: "BEC32607/17"}

{parent_name: "Table 1", child_name: "Table 1.2", documentNo: "BEC32613/17"}

我想像这样转换:

[{
  "parent_name": "Table 1",
  "childs_name": [{ // childs with s

      "child_name": "Table 1.1", // child without s
      "documentsNo": // Documents with s 
      [
        {
          "documentNo": "BEC32568/17" // Document without s
        },
        {
          "documentNo": "BEC32607/17"
        }
      ]

    },

    {
      "childs_name": "Table 1.2",
      "DocumentsNo":
      [
        {
          "DocumentNo": "BEC32613/17"
        }
      ]

    }]
}]

如何在javascript中创建多级JSON对象!

1 个答案:

答案 0 :(得分:0)

JSON是为交换javascript对象信息而创建的文件格式。

这是一种香草JS方式。您可以使用像Ramda或下划线

这样的库来做一些更有趣的事情
var input = [{parent_name: "Table 1", child_name: "Table 1.1", documentNo: "BEC32568/17"},
{parent_name: "Table 1", child_name: "Table 1.1", documentNo: "BEC32607/17"},
{parent_name: "Table 1", child_name: "Table 1.2", documentNo: "BEC32613/17"}];

var output = [];

input.forEach((document) => {
  var parent = output.find(table => table.parent_name === document.parent_name);
  if (!parent) {
    parent = { parent_name: document.parent_name, childs_name: [] };
    output.push(parent);
  }
  var child = parent.childs_name.find(child => child.child_name === document.child_name);
  if (!child) {
    child = { child_name: document.child_name, documentNo: [] };
    parent.childs_name.push(child);
  }
  child.documentNo.push({ documentNo: document.documentNo });
});


var outputJSON = JSON.stringify(output, null, 2);

console.log(outputJSON);