从JSON递归创建对象

文尼森特

我需要从JSON文件创建一个对象。Input 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" }
            ]
         }
      ]
   }
]

代码疯子

您可以使用Object.entriesreduce递归

let obj = {"test":{"Record":1,"RecordValues":{"Address":"3330 Bay Rd.","City":"Los Angeles","SecondObject":{"1":"eins","2":"zwei"}}}}

let recursive = (obj) =>
  Object.entries(obj).reduce((op,[key,value]) => {
  let final = typeof value === 'object' ? {title:key, children:recursive(value)} 
                                        : {title: `${key}: ${value}`}
  return op.concat(final)
},[])


console.log(recursive(obj.test))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章