What is the best way to combine two arrays of objects into a nested tree format?

I am facing a challenge with 2 arrays of objects. Let's call them Array A and Array B.

    [
      { 
        value: 'Node 1',
        id: 1,
        childs: [
          {
            value: 'Node 2',
            id : 2,
            childs: [
              {
                value: 'Node 3',
                id: 3
              },
              {
                value: 'Node 4',
                id: 4           
              }
            ]
          }
        ]
      }
    ] 

Array B looks like this:

    [
      { 
        value: 'Node 1',
        id: 1,
        childs: [
          {
            value: 'Node 5',
            id : 5
          }
        ]
      }
    ]

I am struggling to merge these two arrays into a single tree structure with the desired result shown below:

    [
      { 
        value: 'Node 1',
        id: 1,
        childs: [
          {
            value: 'Node 2',
            id : 2,
            childs: [
              {
                value: 'Node 3',
                id: 3
              },
              {
                value: 'Node 4',
                id: 4           
              }
            ]
          },
          {
            value: 'Node 5',
            id : 5
          }
        ]
      }
    ]

The complexity of the arrays can vary with more nested child objects. How can I achieve the desired output?

Answer №1

Check out the Array#forEach method along with the Array#filter method

var arr = [ { value: 'Node 1', id: 1, childs: [ { value: 'Node 2', id : 2, childs: [ { value: 'Node 3', id: 3 }, { value: 'Node 4', id: 4 
} ] } ] };
var arr2= [ { value: 'Node 1', id: 1, childs: [ { value: 'Node 5', id : 5 } ] }];

arr.forEach(function(a){
    var k =arr2.filter(i=> a.value == i.value);
    a.childs.push(...k[0].childs)
});

console.log(arr)

Answer №2

To effectively combine two arrays containing nested objects, you can utilize a blend of iterative and recursive methodologies by creating a hash map based on unique identifiers for each level.

function mergeArrays(targetArray, sourceArray) {
    var idHash = Object.create(null);
    targetArray.forEach(function (obj) {
        idHash[obj.id] = obj;
    });
    sourceArray.forEach(function (obj) {
        if (idHash[obj.id]) {
            obj.children && mergeArrays(idHash[obj.id].children = idHash[obj.id].children || [], obj.children)
        } else {
            targetArray.push(obj);
        }
    });
}
var array1 = [{ value: 'Node 1', id: 1, children: [{ value: 'Node 2', id: 2, children: [{ value: 'Node 3', id: 3 }, { value: 'Node 4', id: 4 }] }] }],
    array2 = [{ value: 'Node 1', id: 1, children: [{ value: 'Node 5', id: 5 }] }];

mergeArrays(array1, array2);

console.log(array1);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you need to combine arrays, the concat() method is what you're after. Check out more info about it here. Here's how your code could be written:

array1[0].children.concat(array2[0].children);

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

PHP mysterious occurence of undefined index error

I am facing a frustrating issue where I am unable to retrieve any of the headers using my code snippet below: $headers = getallheaders(); echo($headers["SystemTime"]); //This doesn't work $keys = array_keys($headers); echo($headers[$keys[4]]); //This ...

Having trouble transferring data from an aspx file to the code behind using $.ajax({ type: "POST", with Visual Studio 2017 C#?

Utilizing web-forms to gather data from a form and then transmit the data to the code-behind in order to forward it to an API. By clicking on a button, I trigger a JavaScript function that gathers the data and then sends it over to my aspx.cs file for comm ...

How can I efficiently include all css from node_modules in vuejs?

For my Vue.js app built with the webpack template and vuetify, I am starting by importing the vuetify css in my App.vue. <style> @import '../node_modules/vuetify/dist/vuetify.min.css' </style> I'm wondering if this is the c ...

Counting elements in an optional array in Swift

When working with Objective-C, and having the property as shown below: @property (strong, nonatomic) NSArray * myArray; The method to determine the number of objects in myArray would be: - (NSInteger) numberOfObjectsInMyArray { return [self.myArray ...

Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following: for (var i = 0, len = self.Scope.data.length; i < len; i++) { var data = self.Scope.data[i]; var self = this; //Executing First asynchronous function self.EcritureService.createNewDa ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...

Ensure that the JSON file contains values within an array of objects

Currently, I am working with JavaScript and have a JSON file containing Twitter data. Accessing the data is not an issue as I can easily retrieve it using something like: var content = data.text;, allowing me to modify a div using innerHTML. However, I am ...

Complex search queries in Mongodb using Mongoose

Is there a way to create a dynamic search bar that provides suggestions based on user input? For example, as a user types "j", they see options like "Java, JavaScript, JQuery", and when they add "a", they only see "Java, JavaScript". Here is the structure ...

Managing events with classes

I have multiple divs with the same class. When one of these divs is clicked, I want to change the display of the other divs to 'block'. Currently, I am using inline JavaScript for this functionality, but I would like to achieve it without inline ...

What is the best way to dynamically update a React component when a variable changes?

I'm facing an issue where I need to dynamically render the Todo component based on the "currentTodo" value. For example, if my currentTodo is set to 2, then the Todo component should display the object with todoId 2. The challenge here is that the cur ...

Failure to display JavaScript variables within a div element

I'm having trouble displaying my JavaScript variable inside a div column. The value is not showing up, even when I use the inspector tool. However, if I display it outside of any div tags, at the top of the page, it works fine. $(document).ready(fu ...

Dispatch an Ajax message with a specified delay in milliseconds before executing the next action

Hey there, I've been attempting to incorporate a delay() or setTimeOut function into this simple send message script, but I seem to be struggling with the syntax. Whenever I try to add these functions, I encounter numerous syntax errors. Even after fi ...

Why is it that one function does not hold off on execution until Promise.all() is resolved in another function?

I am currently working on a form that allows users to upload files seamlessly. <form @submit.prevent="sendForm" enctype="multipart/form-data"> <input multiple ref="PostFiles" name="PostFiles" type="file" @change="selectFile('add')"> ...

Load the scripts only if they have not already been loaded, and proceed to utilize them

Currently, I have a situation where I must load 4 javascript libraries if they have not been loaded already, and then proceed to utilize their functions. However, I am encountering an issue with Uncaught ReferenceError: sbjs is not defined. Even though th ...

Encountering inaccurate results when solving a set of linear equations using Fortran programming language

I attempted to create a program to calculate the solution of a third-order matrix using the Gaussian elimination method with partial pivoting, but I am obtaining incorrect values. I am struggling to understand the root cause of this issue. Any assistance w ...

Utilize jQuery to retrieve values from a Dropbox and Textbox and populate them inside a table

I'm attempting to retrieve values from a table row using the onfocus event. I have been assigned the task of inserting data into a database without clicking a button, so I decided to utilize the onfocus event for the last cell in the row. The challen ...

An efficient way to store a JavaScript-generated countdown timer in MySQL using PHP

Can anyone provide guidance on how to save a JavaScript-rendered countdown timer into a MySQL database using PHP? For example, I have a button that, when clicked, triggers the countdown timer to start. My issue lies in figuring out the best method to ensu ...

Utilizing JSON Objects to Populate a Knockout Form

I am looking to populate a form using knockout data-binding from a JSON object. I currently have the values hardcoded in my knockout setup, but what I really want to achieve is dynamically populating the form based on a JSON object. Here is a link to my ...

Getting the value of a session variable in JavaScript from a PHP file

Despite the numerous inquiries on this topic, I am still struggling to comprehend it. Scenario: An image with a hyperlink When the image is clicked: Verify if session exists If session exists, open the link If session does not exist, display the login ...

Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user. Table 1 - Story | Table 2 - User api.get('/all_stories', function(req, res) { Story.find({}, function(err, stories) { ...