As a developer, we usually come across a situation wherein we have to update a deeply nested array of objects. For example, say we have an object:

[
    {
        name: 'abc',
        children: [
            {
                name: 'pqr',
                children: [
                    {
                        name: 'xyz',
                        children: []
                    }
                ]
            }
        ]
    },
    {
        name: 'bcd',
        children: [],
    }
]

Alt TextPhoto by Shahadat Rahman on Unsplash

Now in the above array of objects, you have to update the object with the name='xyz', so there are different ways of solving this problem.

  1. Search for some NPM packages or library which does this easily.
  2. Create your method to get this done.

We will opt for option 2 where we are going to use Recursion to solve this problem. Say we know the value of object's key 'name' beforehand where we have to update the children array and we have the array of objects:-

let value = 'xyz';

let list = [
    {
        name: 'abc',
        children: [
            {
                name: 'pqr',
                children: [
                    {
                        name: 'xyz',
                        children: []
                    }
                ]
            },
            {
                name: 'mno',
                children: [
                    {
                        name: 'qrs',
                        children: []
                    }
                ]
            }
        ]
    },
    {
        name: 'bcd',
        children: [],
    }
]

function formatData(arr) {
    arr.forEach(i => {
        if(_.isEqual(i.name, value)) {
            i.children = [...i.children, {
                name: 'New',
                children: []
            }]
        } else {
            formatData(i.children)
        }
    });
}

formatData(list)

Result is

[
   {
      "name":"abc",
      "children":[
         {
            "name":"pqr",
            "children":[
               {
                  "name":"xyz",
                  "children":[
                     {
                        "name":"New",
                        "children":[

                        ]
                     }
                  ]
               }
            ]
         },
         {
            "name":"mno",
            "children":[
               {
                  "name":"qrs",
                  "children":[

                  ]
               }
            ]
         }
      ]
   },
   {
      "name":"bcd",
      "children":[

      ]
   }
]

Here we are iterating over the list and checking whether the current value matches any of the child element's 'name' value and if it does then we update the object or we recursively go inside the array of objects.

What are your thoughts, do you think there is a better way of doing this, then please suggest!

Happy learning and coding !!

This post is also available on DEV.