简体   繁体   中英

Normalize deeply nested objects

So I have this object which represents a hierarchy. What Is the best way teaverse it?

For example finding the number of friends at each level, adding a friend at a specific depth.

{
  "name": "John",
  "Friends": [{
      "name": "Emily",
      "Friends": [{
          "name": "Sandra",
          "Friends": []
        },
        {
          "name": "Michael",
          "Friends": []
        }
      ]
    },
    {
      "name": "Sara",
      "Friends": [{
          "name": "James",
          "Friends": []
        },
        {
          "name": "Yara ",
          "Friends": []
        }
      ]
    }
  ]
}

This function should suffice, this will give us capability to iterate breadth wise and we can add/remove objects if we want with some other conditional statements -:

function traverseObjectBreadthWise (obj) {
    for (var key in obj) {
        if (typeof obj[key] == "array" || typeof obj[key] == "object") {
            traverseObjectBreadthWise(obj[key]);
            console.log(key);
        } else {
            console.log(key, "=", obj[key]);
        }
    }
}

I suggest to you use lodash.Its so usefull.You can use count by and you can find count for each level of friends.I use it lik recursive because Friends level can be more.

  recusersiveFunc(arr){
    if(Object.keys(arr).includes("Friends")){
        console.log(_.countBy(arr.Friends,"name"));
        arr.Friends.forEach(x => {
          this.recusersiveFunc(x);
        });             
    }
  }

    this.recusersiveFunc(data);//data is your JSON object

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