我需要从一个JSON文件创建一个对象。 输入的JSON文件的格式如下。
{
"test":{
"Record":1,
"RecordValues":{
"Address":"3330 Bay Rd.",
"City":"Los Angeles",
"SecondObject":{
"1":"eins",
"2":"zwei"
}
}
}
}
我所做的是这个函数...
var test = [];
function recFunc(obj, parent_id = null) {
for(var i in obj) {
if(typeof obj[i] == "object" && obj[i] !== null) {
test.push({title: i, children: []});
recFunc(obj[i], (test.length-1));
}else {
if(parent_id != null) {
test[parent_id].children.push({title: (i + " : " + obj[i])});
}else {
test.push({title: (i + " : " + obj[i])});
}
}
}
return test;
}
输出对象应如下所示。
[
{ "title":"Record : 1" },
{
"title":"RecordValues",
"children":[
{ "title":"Address : 3330 Bay Rd." },
{ "title":"City : Los Angeles" },
{
"title":"SecondObject",
"children":[
{ "title":"1 : eins" },
{ "title":"2 : zwei" }
]
}
]
}
]