[英]Generating multi-level JSON javasacript
I've never used JSON before so I'm not familiar with its syntax.我以前从未使用过 JSON,所以我不熟悉它的语法。
At the moment I have multiple arrays containing different pieces of data.目前我有多个包含不同数据的数组。
I would like to create one JSON object, that contains the multiple arrays each with several pieces of data.我想创建一个 JSON 对象,其中包含多个数组,每个数组都有几条数据。
I have an array of Objects, example :我有一个对象数组,例如:
{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"}
I want to convert like this :我想这样转换:
[{
"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"
}
]
}]
}]
How can I create a multilevel JSON object in javascript !如何在 javascript 中创建多级 JSON 对象!
Well JSON is a file format created for exchanging javascript object information.那么 JSON 是一种为交换 javascript 对象信息而创建的文件格式。
Here is a vanilla JS way to do it.这是一个香草 JS 方法来做到这一点。 You could do something a bit fancier with a library like Ramda or underscore你可以用 Ramda 或 underscore 之类的库做一些更有趣的事情
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.