Search code examples
javascriptarraysjavascript-objects

Concentate values in a Nested Array of Object with children in JavaScript


I have a nested array of objects having path as one of the keys. The structure of the nested array is as under:

const data = [
    {
        Name: "item1",
        path: "path1",
        children:[
            {
                Name: "item1.1",
                path: "path1.1"
            },
            {
                Name: "item1.2",
                path: "path1.2",
                children:[
                    {
                        Name: "item1.2.1",
                        path: "path1.2.1",
                        children:[
                            {
                                Name: "item1.2.1.1",
                                path: "path1.2.1.1"
                            }
                        ] 
                    },
                ]
            }
        ]
    }
]

I need to concentate the path values without changing the structure of array. The expected result would be:

const newdata: [
    {
        Name: "item1",
        path: "path1",
        children:[
            {
                Name: "item1.1",
                path: "path1/path1.1"
            },
            {
                Name: "item1.2",
                path: "path1/path1.2",
                children:[
                    {
                        Name: "item1.2.1",
                        path: "path1/path1.2/path1.2.1",
                        children:[
                            {
                                Name: "item1.2.1.1",
                                path: "path1/path1.2/path1.2.1/path1.2.1.1",
                            }
                        ] 
                    }
                ]
            }
        ]
    }
]

How to do it in JavaScript?


Solution

  • This would be best done with a recursive Function, that iterates through your entire data structure and sets the Path by building it up while traversing your data structure.

    The first version creates the path information from scratch, by using the index of each child in the array and building up the index that gets appended to the path string.

    Further below i've provided changes to this version, that uses the already existing path information and concatenates the path string as you asked for.

    // Recursive Function to iterate through a possible endless nested data structure
    // We provide the parameter for the previous index and parentPath to build up the path string
    function recursivePath(data, index = "", parentPath = "") {
    
      // We will get an Array with all Items as 'data' which we will loop with forEach
      data.forEach((item, i) => {
    
        // We recreate the the index of the item by adding current index of 
        // this item in the data array to the index structure of the parent items
        let itemIndex = index !== "" ? `${index}.${i+1}` : `${i+1}`;
    
        // We do the same for the path, we take the path of the parent 
        // and add the path information of this item to it.
        let itemPath = `${parentPath}path${itemIndex}`;
    
        // We set the path property of this item, which will be returned 
        // after all items of this data are done.
        item.path = itemPath;
    
        // We check if this item has some nested childrens and if it does, 
        // we will repeat this process for all those childrens
        if (item.children && typeof item.children.length) {
    
          // We provide the newly created index on which those childs will build upon 
          // as the same with the path.
    
          // This can be a bit confusing, but we assume here, that the function will return 
          //the finished childrens and we save the result to our childrens property.
          item.children = recursivePath(item.children, itemIndex, itemPath + "/");
        }
      });
    
      // Lastly we iterated through all Items and are sure to set the Path for all Items 
      // and their childrens nested inside and return the entire data array.
      return data;
    }
    
    
    // Your Data
    const data = [{
      Name: "item1",
      path: "path1",
      children: [{
          Name: "item1.1",
          path: "path1.1"
        },
        {
          Name: "item1.2",
          path: "path1.2",
          children: [{
            Name: "item1.2.1",
            path: "path1.2.1",
            children: [{
              Name: "item1.2.1.1",
              path: "path1.2.1.1"
            }]
          }, ]
        }
      ]
    }];
    
    // We use the recursive function and output the results to the console
    console.log(recursivePath(data));

    If you would use the stored Path value of each item, you could just append the Value onto the parentPath String and save this new String into item.path

    You would just change the line in the function, that creates the itemPath a little bit and you can remove the line that creates the itemIndex.

    The parameter itemIndex of the recursive function isn't needed anymore and can be removed too.

    // We wont need the index anymore, as we use the already existing 
    // Path value for the Index of each item
    function recursivePath(data, parentPath = "") {
      // We create a temporary new Data variable, to hold our changed elements.
      let newData = [];
      
      data.forEach((item, i) => {
        // We'll create a copy of an Object to modify
        let copyItem = {};
        // Object.assign() copies all enumerable properties of one object to another
        // We'll then use the new object to modify all properties, 
        // thous the original item will be untouched.
        Object.assign(copyItem, item)
      
        // We append the path information of this items path value
        // onto the parentPath string
        let itemPath = `${parentPath}${item.path}`;
    
        // Same as before
        copyItem.path = itemPath;
    
        // Same as before
        if (copyItem.children && typeof copyItem.children.length) {
        
          // We removed the itemIndex, as it isnt needed anymore
          copyItem.children = recursivePath([...copyItem.children], itemPath + "/");
        }
        
        // After modification we add the object to the temporary array 
        // and return it after all items are modified.
        newData.push(copyItem);
      });
      
      // Returning the newly created array
      return newData;
    }
    
    
    // Your Data
    const data = [{
      Name: "item1",
      path: "path1",
      children: [{
          Name: "item1.1",
          path: "path1.1"
        },
        {
          Name: "item1.2",
          path: "path1.2",
          children: [{
            Name: "item1.2.1",
            path: "path1.2.1",
            children: [{
              Name: "item1.2.1.1",
              path: "path1.2.1.1"
            }]
          }, ]
        }
      ]
    }];
    
    // We use the recursive function and output the results to the console
    console.log(recursivePath(data));
    console.log(data);

    Fur further clarification of why we need to copy Arrays and/or Objects provided as a parameter:

    Arrays and Objects arent provided as their full content, as those could be huge data structures and moving and copying those every time they are provided as parameter would cause a huge memory dump as every parameter would be a redundant content of their original data. Therefore only references or in other languages called pointers are provided, which point or reference the memory location, where the content is stored.

    If you provide an array or object for a function and modify them, the modification will be stored via the reference on the original array and therefore all further access to this variable will also have those modification.

    Thats why we need to copy the content of those variables into new array or objects and return those as they are themself new references but to another array with the same but slightly modified content. The redundancy doesn't matter, as those variables are only block/closure scoped with the prefix of let before, therefore they are garbage collected after the function resolved.