从JSON递归创建对象

时间:2019-04-13 07:53:52

标签: javascript jquery arrays json recursion

我需要从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" }
            ]
         }
      ]
   }
]

3 个答案:

答案 0 :(得分:1)

这是一种可能的方法,递归地遍历Object.entries

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

const makeNested = (currInput) => {
  return Object.entries(currInput).map(([key, val]) => (
      typeof val !== 'object'
      ? { title: `${key} : ${val}` }
      : {
          title: key,
          children: makeNested(val)
        }
  ))
};
console.log(makeNested(input.test));

答案 1 :(得分:1)

如果嵌套值是一个对象,则可以使用Object.entries()并递归调用该函数:

Object(value) === value检查value是否是不是null的对象)

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

function transform(obj) {
  return Object.entries(obj).map(([key, value]) => {
    if(Object(value) === value)
      return { title: key, children: transform(value) }
     else
      return { title: `${key} ${value}` }
  })
}

console.log(transform(obj.test))

答案 2 :(得分:1)

您可以将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))