如何遍历一个复杂的多级json字符串来创建Angularjs或Javascript中的对象?

np8igboo  于 2022-10-31  发布在  Angular
关注(0)|答案(1)|浏览(151)

我有一个Json字符串,如下所示:

var json =     "[{"Id":"1234",
        "FirstName":"One",    
        "Index":"32",
        "Type":"t1",
        "Children":[{"Id":"976","FirstName":"Two","Index":"32","Type":"t2",     

           "Children":[{"Id":"428",
               "FirstName":"Three",            
               "Index":"32",
               "Type":"t3",
               "Children":[],
               "ParentId":"f235"}],        

        "ParentId":"f826"}],
     "ParentId":"0000"}]"

我想创建一些只有ID、FirstName、Children字段的对象,而不是Index和Type字段。每个对象也有一些子服务。
因此,obj1将具有属性Firstname、ParentId和Children,如果您向下钻取到其Children,则它将具有另一个ID为firstname、ParentId的对象,如果向下钻取,则没有其他Children

I began by doing something like 

    var servicejson = JSON.parse(jsonStr);
     for (let i = 0; i < servicejson).length; i++) {
            var parentnode = {
                Id: servicejson[i].Id,
                FirstName: servicejson[i].JsonValue,        
                ParentId: servicejson[i].ParentId,             
            };        

            //check if children
            if (servicejson[i].Children.length > 0) {
                //do something here ??
            }
    }

有一个对象,其中有一个子节点,在子节点中还有另一个子节点。我把这些分配给对象,或者推到对象上的一个数组,因为我假设它可能需要一个递归调用来分配子数组,这就是我需要一些帮助的地方。

cfh9epnr

cfh9epnr1#

你可以这样做

var json =     [{"Id":"1234",
        "FirstName":"One",    
        "Index":"32",
        "Type":"t1",
        "Children":[{"Id":"976","FirstName":"Two","Index":"32","Type":"t2",     

           "Children":[{"Id":"428",
               "FirstName":"Three",            
               "Index":"32",
               "Type":"t3",
               "Children":[],
               "ParentId":"f235"}],        

        "ParentId":"f826"}],
     "ParentId":"0000"}]

const transform = ({Id, FirstName, Children}) => ({
  Id,
  FirstName,
  Children: Children.map(transform)
})

const result = json.map(transform)

console.log(result)

相关问题