Home > Back-end >  Javascript nested object recursive
Javascript nested object recursive

Time:01-26

So ,i did my research and so far i cannot find any good solution to my problem...

so i have an object approach so i have tried a recursive function but it doesnt work at all (why i am here)

this function go thru one layer and stops she finds that id 3 , id 11 have both 1 childrens , while i want it to go deeper

i hope it is not a duplicate post

and i thank you in advance

#function

const haveChild = (obj, parent_id=0) =>{
        for (const [key,value] of Object.entries(obj)){
            if (value && typeof value === "object"){
                if (value['childrens']){
                    for (const [k,v] of Object.entries(value.childrens)){
                        haveChild(v,v.parent_id)
                        console.log('-----',v.name,'parent id= ',v.parent_id)

                    }
                }else{

                }
            }

        }

#data from API


{ 
    "2": {
      "id": "2",
      "parent_id": "0",
      "name": "name1"
    },
    "3": {
      "id": "3",
      "parent_id": "0",
      "name": "name2",
      "childrens": {
        "9": {
          "id": "9",
          "parent_id": "3",
          "name": "name3"
        }
      }
    },
    "11":{
      "id": "11",
      "parent_id": "0",
      "name": "name4",
      "childrens": {
        "16": {
          "id": "16",
          "parent_id": "11",
          "name": "name5",
          "childrens": {
            "21": {
              "id": "21",
              "parent_id": "16",
              "name": "name6",
              "childrens": {
                "23": {
                  "id": "23",
                  "parent_id": "21",
                  "name": "name7"
                }
              }
            }
          }
        }
      }
    } 
}

CodePudding user response:

the problem is that the first time you call the function, in the for loop, key is the key of every object and value the corresponding value

But from the second time key is the name of the attribute and value the value of the attribute So you have to create another object in this way:

{[k]: v}

I also move the console.log outside the inner for loop

const haveChild = (obj, parent_id=0) =>{
        for (const [key,value] of Object.entries(obj)){
            if (value && typeof value === "object"){
                if (value.childrens){
                    for (const [k,v] of Object.entries(value.childrens)){
                        haveChild({[k]: v},v.parent_id)
                    }
                }
                console.log('-----',value.name,'parent id= ',value.parent_id);
            }
       }
}
  •  Tags:  
  • Related