Is it possible to combine the values of parents in an array of deeply nested objects?

I have an array containing nested objects that need their id property updated by combining all parent names.

The id should be the current node's name value joined with its parents' names, separated by '/'.

treeData = [{
    name: 'Infiniti',
    id: '',
    children: [{
        name: 'G50',
        id: '',
        children: [{
            name: 'Pure AWD',
            id: ''
          },
          {
            name: 'Luxe',
            id: ''
          },
        ],
      },
      {
        name: 'QX50',
        id: '',
        children: [{
            name: 'Pure AWD',
            id: ''
          },
          {
            name: 'Luxe',
            id: ''
          },
        ],
      },
    ],
  },
  {
    name: 'BMW',
    id: '',
    children: [{
        name: '2 Series',
        id: '',
        children: [{
            name: 'Coupé',
            id: ''
          },
          {
            name: 'Gran Coupé',
            id: ''
          },
        ],
      },
      {
        name: '3 Series',
        id: '',
        children: [{
            name: 'Sedan',
            id: ''
          },
          {
            name: 'PHEV',
            id: ''
          },
        ],
      },
    ],
  },
];

Expected Result

[{
    name: 'Infiniti',
    id: 'Infiniti',
    children: [{
        name: 'G50',
        id: 'Infiniti/G50',
        children: [{
            name: 'Pure AWD',
            id: 'Infiniti/G50/Pure AWD'
          },
          {
            name: 'Luxe',
            id: 'Infiniti/G50/Luxe'
          },
        ],
      },
      {
        name: 'QX50',
        id: 'Infiniti/QX50',
        children: [{
            name: 'Pure AWD',
            id: 'Infiniti/QX50/Pure AWD'
          },
          {
            name: 'Luxe',
            id: 'Infiniti/QX50/Luxe'
          },
        ],
      },
    ],
  },
  {
    name: 'BMW',
    id: 'BMW',
    children: [{
        name: '2 Series',
        id: 'BMW/2 Series',
        children: [{
            name: 'Coupé',
            id: 'BMW/2 Series/Coupé'
          },
          {
            name: 'Gran Coupé',
            id: 'BMW/2 Series/Gran Coupé'
          },
        ],
      },
      {
        name: '3 Series',
        id: 'BMW/3 Series',
        children: [{
            name: 'Sedan',
            id: 'BMW/3 Series/Sedan'
          },
          {
            name: 'PHEV',
            id: 'BMW/3 Series/PHEV'
          },
        ],
      },
    ],
  },
];

I attempted to use Array.prototype.reduce() but struggled to concatenate the previous value.

    function updateTreeData(array) {
      return array.reduce((returnValue, currentValue) => {
        if (currentValue.children != null) {
          returnValue.push(Object.assign({}, currentValue, {
            children: this.updateTreeData(currentValue.children)
          }))
        }
        return returnValue
      }, []);
    }

    console.log(updateTreeData(treeData))

Answer №1

If you're looking for a solution, consider implementing the recursion method.

const treeData=[{name:"Toyota",id:"",children:[{name:"Corolla",id:"",children:[{name:"LE",id:""},{name:"SE",id:""}]},{name:"Camry",id:"",children:[{name:"XSE",id:""},{name:"Hybrid",id:""}]}]},{name:"Honda",id:"",children:[{name:"Civic",id:"",children:[{name:"Sedan",id:""},{name:"Hatchback",id:""}]},{name:"Accord",id:"",children:[{name:"Sport",id:""},{name:"Touring",id:""}]}]}];

const assignId = (list, parent) => {
    for(const item of list) {
     if(!parent) {
           item.id = item.name
     } else {
        item.id = parent + '/' + item.name
     }
     if(item.children) {
        assignId(item.children, item.id)
     }
  }
}

assignId(treeData)

console.log(treeData)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ng-change directive in Angular is failing to trigger for checkboxes

I am facing an issue with my code. The ng-change event of individual checkboxes is not triggered when I click the Select All button, but it works fine when I select them individually. I want the itemChecked method to be called when the Select All button is ...

Mastering the functionality of array.map()

Apologies for the simplicity of my query. I am in the process of streamlining some code and have been exploring the use of array.map rather than traditional for loops to iterate through arrays and using array.push. I've managed to grasp the fundament ...

Error encountered in MySQL and NodeJS: Unable to add new query after invoking quit with transactions

While working on implementing MySQL for NodeJS and Restify, I encountered a flawless experience with queries. However, when attempting to utilize data updating functionality through transactions, I faced the error message: Error: Cannot enqueue Query after ...

Increase the value of a number using jQuery

When using jquery to animate a random number increment from 0001 to 1000, the issue arises when reaching the number 0077. The final number displayed is 77 instead of 0077. Is there a solution to ensure the format remains as 0077? Your help is appreciated. ...

Tips for removing files from an <input type='file' /> element with jQuery or JavaScript

I have multiple <input type='file' /> fields in my file without any HTML form. I need to clear the attached files from a specific <input type='file' />, not all of them. Using $('input').val(""); clears all the < ...

Creating an Android game with the utilization of HTML5 and Javascript involves the adaptation of images to various screen resolutions

Currently, I am working on creating a basic game for android devices by utilizing HTML5, javascript, and cordova for wrapping it up. One of the key features of my game will involve using an image as a background and animating it to create a dynamic visua ...

Is there a way to access a variable declared in index.js from a controller?

Currently, I am experimenting with forms-angular (). In my index.js file, I have defined a variable called DataFormHandler. However, I am facing an issue trying to access this variable in my controllers. The setter app.set("formHandler", DataFormHandler) ...

A method to verify the presence of a specific element within a list using JavaScript

I'm trying to validate if the list retrieved from the application contains the expected element. Can you please review my code and let me know where I might be making a mistake? this.verifyOptionsInDropdown = async function(){ var optionList = a ...

Ways to update a row in ui-grid?

I am attempting to refresh only the specific row that has been edited in the ui-grid without refreshing the entire table. My scenario involves editing a row in the grid, triggering a rest call, and then updating only that particular row in the grid. Upon ...

Changing the tooltip background color in FullCalendar 6 and Bootstrap 5: A step-by-step guide

My FullCalendar agenda displays events with colored backgrounds. However, I want the tooltips for these events to have matching background colors as well. Currently, the tooltips always show up with a black background. Is there a way to dynamically change ...

The transmission of ContentType is unsuccessful

I'm having an issue with the code in my app. It seems that the content-type is not being sent. Is there a way to force it to be sent? $.ajax({ crossDomain: true, type: ...

Using a jQuery UI accordion with a numbered list

As part of my company's user documentation, I am trying to integrate jQuery UI components into our HTML output. Despite my limited experience with JavaScript, I was able to get the accordion feature working for table rows. However, I am now facing dif ...

The script from 'URL' was declined for execution due to its MIME type of 'text/html' which is non-executable, in addition to strict MIME type checking being enabled

I encountered an error stating "Refused to execute script from 'URL' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled." The code that triggered this error is shown below. <!DOCTYPE htm ...

"Utilizing the usePrevious hook in React: A step-by-step

After referencing the React documentation, it seems like I may not be using this code correctly. import { useEffect, useRef } from 'react'; export default function usePreviousState(state) { const ref = useRef(); useEffect(() => { ref ...

What is the method for utilizing HSL instead of RGB in the global declaration of SCSS using the JavaScript API

This is how my next.config.js file is structured: // next.config.js const env = require('./site.config').env; const Colour = require('sass').types.Color; const {r, g, b} = require('./site.config').customProperties; const wit ...

Surprising outcomes arise when the results of Three.js EffectComposers are combined, as the Additive and Subtractive effects interact in unexpected

While working on postprocessing in Three.js with EffectComposers and shader passes, I encountered some unexpected behavior when combining the WebGLRenderTargets (renderTarget2) from different composers. My setup involves five composers: three to render sce ...

Having trouble adding a property to an object, any solutions?

I've been struggling with adding a property to a nested Object in my JavaScript code. Despite setting the property name and value, the property doesn't seem to persist. populated_post.comments[i].comment.end = true console.log(typeof(populated_po ...

Leveraging em units in jQuery Script

I'm currently in the process of building a website and I'm facing an issue with converting measurements to em's. The script that I have reused from a previous project only seems to work with pixels, despite my efforts to make it compatible w ...

What is the best way to adjust the specific scope of every element generated by ng-repeat within a directive?

Attempting to simplify tables in Angular, I am working on a directive. My goal is for the user to only need to provide the list object and the formatting of each list element in the HTML, using the my-table tag as shown below... <h3>My Table</h3& ...

the value of properrty becomes undefined upon loading

In my code, there exists an abstract class named DynamicGridClass, containing an optional property called showGlobalActions?: boolean?. This class serves as the blueprint for another component called MatDynamicGridComponent, which is a child component. Ins ...