Optimal method for restructuring an array of objects

Looking to restructure an array of linked objects into a single tree object sorted by ID. Since the depth is unknown, considering recursion for efficiency. What's the best approach?

The initial array:

const arrObj = [
  {
    "id": 1,
    "children": [
      {
        "id": 2
      },
      {
        "id": 3
      }
    ]
  },
  {
    "id": 2,
    "children": [
      {
        "id": 4
      },
      {
        "id": 5
      }
    ]
  },
  {
    "id": 3,
    "children": [
      {
        "id": 6
      }
    ]
  },
  {
    "id": 4
  }
]

The desired tree structure:

const treeObj = {
  "id": 1,
  "children": [
    {
      "id": 2,
      "children": [
        {
          "id": 4
        },
        {
          "id": 5
        }
      ]
    },
    {
      "id": 3,
      "children": [
        {
          "id": 6
        }
      ]
    }
  ]
}

Other properties are present in each object.

Answer №1

A recursive mapping function can be utilized to iterate over all the children.

const arrObj = [ { "id": 1, "children": [ { "id": 2 }, { "id": 3 } ] }, { "id": 2, "children": [ { "id": 4 }, { "id": 5 } ] }, { "id": 3, "children": [ { "id": 6 } ] }, { "id": 4 } ];
const res = arrObj[0];//assuming the first element is the root
res.children = res.children.map(function getChildren(obj){
  const child = arrObj.find(x => x.id === obj.id);
  if(child?.children) child.children = child.children.map(getChildren);
  return child || obj;
});
console.log(res);

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

JavaScript Transformation of Date Format

var dt="29/05/2013"; //DD/MM/YYYY I am looking to change the format to yyyy/MM/dd; My current approach is: var newdate=dt.getFullYear()+"/"+dt.getMonth()+"/"+dt.getDate(); Is there a more straightforward way to convert it without using substring? No p ...

Exploring the use of Generics in Swift 5 for parsing JSON - comparing parsing from local files to

These are the two functions I've created to handle JSON parsing in Swift. The first one works perfectly with any JSON data I provide. However, the second function is causing me some trouble. It's supposed to do the same thing as the first one, b ...

Developing dynamic forms within arrays using AngularJS

Hey there! I've got a scenario where I have an array of people in my dynamic application. Each person, such as James, Bob, and Walter, has their own set of data that needs to be filled out using simple directives. $scope.users = [ { name: ...

Warning: Node 125008 has reached the maximum number of listeners, indicating a potential memory leak in the EventEmitter

(node:125008) MaxListenersExceededWarning: There may be a memory leak with EventEmitter as 11 ready listeners have been added. Try using emitter.setMaxListeners() to raise the limit Can anyone provide guidance on how to increase the listener event count? ...

Transferring information among various instances of a single controller (ng-controller)

I am relatively new to using Angular and I am facing a challenge with a seemingly simple task that is proving to be more complex within the framework. The issue at hand involves data manipulation, specifically with a variable named var1. I am modifying th ...

Is jQuery Table a Suitable Replacement for GridView in an ASP.NET Web Application?

This web application utilizes SQL DB connections and web services to allow users to insert, edit, and delete database records. However, we are currently facing challenges in providing the required features for a dry run demo due to certain cosmetic limitat ...

Associate the name of the input field with an array where the values of the input field serve as

My input fields are as follows: <input name='223' type='number' class='form-control score' value='70'> <input name='224' type='number' class='form-control score' value='65& ...

Exploring the React component life cycle: Understanding the distinction between render and return, and what happens post-return

This question pertains to the concepts surrounding react component life cycles. Below is an example code snippet provided as a general reference. const Modal = ({ className, variant, width, withCloseIcon, isOpen: propsIsOpen, onClose: tellParen ...

I'm encountering a status 415 error when trying to post to the Spotify API for tokens. Is there something I'm

My approach to interfacing with their API for the Authorization Code Flow is as follows: class func obtainAuthTokenPackage(authCode: String) throws { //Initiate a request var request = URLRequest(url: Gimme.theSpotify.urlFor(endpoint: .requestingT ...

Unable to initiate npm start due to author problem

I ran into an issue when trying to start npm in the command prompt: package.json: { "name": "reactapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "webpack-d ...

Check for duplicates within 2 arrays by implementing a filtering process

I am trying to figure out how to compare two arrays to determine if there are any duplicates within them. const result = this.specialRange.filter(d => !dayMonth.includes(d)); What I have attempted so far just returns the entire array back to me, but I ...

Parsing JSON data containing multiple types of objects is made simple with JSON.net

Is there a way to deserialize a list of various objects using JSON.net? string myJson = "[{action: 'a1', target: 4},{action: 'a2', targets: [1,2,3], {action:'a3', text:'targets altered'}}]"; In this scenario, we ha ...

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I ne ...

d3 bar chart with overlapping bars - define x and y coordinates

Here is a glimpse of the data I am working with: var students = [ {'race': 'Black', 'count': 7, 'year': 2004, 'allnames': ['G Brown', 'F Clarkson', 'E Miller', 'R Black& ...

Getting the return value from a confirm box in ASP.NET C#

Despite reading through numerous similar questions and answers, I am still unable to find a solution to my problem. I am working on a form that allows users to select a file and choose a date for importing the file. If the selected date is before the last ...

Type parameter in express.js route

If I have this specific route in my Express.js server: router.get('/ad/:id', (req, res) => { const { id } = req.params Ad.getAd(id, (err, resp) => { if(err){ return handleError('Failed to load an ad' ...

What is the best way to send the value of this variable through the parameters?

In jQuery: initializeSliders(socket, '!{requestData}'); requestData is a special object (an HTTP request object in my Express.js web application) that contains information such as my session. However, when I pass this object into the initialize ...

When a checkbox is within a container that contains images, it will trigger the event twice

I'm facing an issue with the Google map on my website. Whenever a marker is clicked, an infowindow opens with a checkbox that has a unique id. When this checkbox is checked, a console message is triggered. Below is the code snippet: function initiali ...

What is the proper way to confirm the authenticity of a captcha code

hey there, I'm struggling with my captcha code. The issue is that it still accepts wrong captchas when entered in the input box. Can someone guide me on how to validate the wrong captcha entry? Here's my form code: <p class="Captcha" style=" ...

Google Maps Shifting Focus

I'm currently working on an AngularJS app that involves multiple locations, and the goal is for users to click on a location which then redirects them to the specific spot on Google Maps. However, I've encountered an issue when trying to relocate ...