Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 -:

functiontraverseObjectBreadthWise (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]);
        }
    }
}

Solution 2:

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

Post a Comment for "Normalize Deeply Nested Objects"