Home > OS >  How to update a recurring nested object property using its previous value using Javascript?
How to update a recurring nested object property using its previous value using Javascript?

Time:03-29

I got an array with some elements and each element has some properties like name, id and children. Each element has children property and then sub children so on and so forth. This array is already there in our application. Now I want to update all of elements and sub elements of our array with a new property called "path". The "path" will be the key and its value will be the addition of its previous object's name. For example

    let dataArray = [
      {
        name: 'Data',
        id: 12,
        path: 'Data',
        children: [
          {
            name: 'Data Center',
            id: 13,
            path: 'Data/Data Center',
            children: [
              {
                name: 'Data Management',
                id: 13,
                path: 'Data/Data Center/Data Managemet',
              },
            ],
          },
        ],
      },
      {
        name: 'Machine',
        id: 12,
        path: 'Machine',
        children: [
          {
            name: 'Machine Center',
            id: 13,
            path: 'Machine/Machine Center',
            children: [
              {
                name: 'Machine Management',
                id: 13,
                path: 'Machine/Machine Center/Machine Managemet',
              },
            ],
          },
        ],
      }
    ];

As you can see path property to all the elements. I want to make this happen programatically. For that, here is the piece of code I have written but I am not able to understand what need to need to be done to achieve. This piece of code adds path property to all the elements and sub elements but with name as path like above example. I want the addition of previous names which have been traversed.

    addPathProperty(){
    dataArray.forEach((element) =>{
        element.path = element.name;
        if(element.children.length > 0){
            this.addPathProperty(element.children)
        }
    });
}

Here is the link Stackblitz. Any help will be appreciated. Thank you

CodePudding user response:

I think this code should work:

const appendPath = (root = '') => (obj) => {
  obj.path = root ? `${root}/${obj.name}` : obj.name

  if (obj.children) {
    obj.children.forEach(appendPath(obj.path))
  }
}

dataArray.forEach(appendPath())

appendPath is a function that accepts a root, when this function is invoked, it will combine root and name and set this to object.path; After that, it will do the same for the object.children if they exists

  • Related