简体   繁体   中英

how to get inner most child of a JSON data

I have a JSON data which is something like this, And my requirement to fetch the data of inner most children ie hierarchyLevel: 4 . And this JSON data is not static, the hierarchyLevel can go any thing like 5, 6, 7 any thing. Please help to find solution in javascript.

{
  "hierarchylist": [
    {
      "hierarchyId": 10,
      "hierarchyLevel": 0,
      "name": "ABC",
      "parentId": 0,
      "children": [
        {
          "hierarchyId": 12,
          "hierarchyLevel": 1,
          "name": "ABC-Child1",
          "parentId": 10,
          "children": [
            {
              "hierarchyId": 2,
              "hierarchyLevel": 2,
              "name": "People Management & Development1 ",
              "parentId": 12,
              "children": [
                {
                  "hierarchyId": 5,
                  "hierarchyLevel": 3,
                  "name": "Resourcing2_1",
                  "parentId": 2,
                  "children": [
                    {
                      "hierarchyId": 19,
                      "hierarchyLevel": 4,
                      "name": "Resource Request ",
                      "parentId": 5,
                      "children": [],
                      "docId": 19,
                      "docstatusid": 20
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

Thanks.

This should get you the inner-most one:

 let data = { "hierarchylist": [ { "hierarchyId": 10, "hierarchyLevel": 0, "name": "ABC", "parentId": 0, "children": [ { "hierarchyId": 12, "hierarchyLevel": 1, "name": "ABC-Child1", "parentId": 10, "children": [ { "hierarchyId": 2, "hierarchyLevel": 2, "name": "People Management & Development1 ", "parentId": 12, "children": [ { "hierarchyId": 5, "hierarchyLevel": 3, "name": "Resourcing2_1", "parentId": 2, "children": [ { "hierarchyId": 19, "hierarchyLevel": 4, "name": "Resource Request ", "parentId": 5, "children": [], "docId": 19, "docstatusid": 20 } ] } ] } ] } ] } ] } let children = data.hierarchylist[0].children; while(children[0] && children[0].children && children[0].children.length) { children = children[0].children; } console.log(children);

You can try the while loop, here's the example

var children = json['hierarchylist']['children'][0];

while(typeof children !== 'undefined') {
    children = children['children'][0];
}

console.log(children);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM