Combining modifications from one array into the original array using Javascript

Initially, I have an array structured like this:

[{
    name: 'a',
    color: 'red',
    children: 
    [{
        name: 'a1',
        color: 'red',
        children: 
        [{
            name: 'a11'
        }]
    },
    {
        name: 'a2'
        color: 'red',
    }]
},
{
    name: 'b'
    color: 'red',
}]

After some user interaction on the frontend, I receive an updated array structure:

[{
    name: 'a'
    color: 'red',
    children: 
    [{
        name: 'a1'
        color: 'red',
    },
    {
        name: 'a2'
        color: 'red',
        children: 
        [{
            name: 'a21',
            color: 'yellow'
        }]
    }]
},
{
    name: 'new'
    color: '',
},
{
    name: 'a11'
    color: 'red',
},
{
    name: 'b'
    color: 'red',
}]

This update includes objects that have moved and new objects. The challenge is merging these changes back into the original array without altering the unchanged objects.

Since the array is rendered using Angular, a simple replacement of the original array with the updated one can lead to performance issues, especially with large arrays.

I attempted to use the merge function in lodash, but encountered issues with object properties conflicting, such as the object "new" inheriting the color "red" from the object "b".

What would be the most efficient approach to handle this scenario?

Answer №1

If you are working with Angular, you can take advantage of the built-in function angular.merge() which is designed to handle scenarios like the one you are facing. Just make sure to verify its compatibility with the version of Angular you are using.

Check out the key line of code below.

angular.merge($scope.source, $scope.changed);

With this code snippet, the changes in $scope.changed will be merged into $scope.source directly without the need for an additional left-hand side (LHS) variable.

In order to better understand how this works, you can take a look at the following JSFiddle demonstration that I have prepared. Feel free to test and see if it resolves your issue!

JSFiddle Demo

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 function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

Exploring for JSON keys to find corresponding objects in an array and adding them to the table

I'm currently working on a project where I need to extract specific objects from a JSON based on an array and then display this data in a table. Here's how my situation looks: playerIDs: number[] = [ 1000, 1002, 1004 ] The JSON data that I am t ...

Tips for executing a never-ending blocking operation in NodeJS?

Currently, I have a collection of API endpoints within Express. One specific endpoint triggers a lengthy process that hinders the flow of other incoming requests in Express. I am determined to transform this process into a non-blocking one. In order to ga ...

What is the best way to ensure that a child div can expand to fit within the scrollable area of its parent div

I am facing an issue with a parent div that changes size based on the content inside it. When the content exceeds the initial size, causing the parent to scroll instead of expanding, I have a child div set to 100% width and height of the parent. However, t ...

Accessing JSON data from the Public folder in a create-react-app

I have a JSON file called ipAddress.json with the following content: { "ipAddress": "11.111.111.111" } To access this file, I placed it in an "ipAddress" folder within the public directory. So now the path is "public/ipAddress/ipAddress.json". However, ...

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

Using Angular-Leaflet-Directive to display JSON markers on a map

I am attempting to create a Leaflet Map with clustering markers in my application. I am using the Angular Leaflet Directive plugin for this task. It works perfectly with the example controller and JSON data provided, but I am facing a challenge with gettin ...

Exploring the concept of inheritance in JavaScript and Angular programming

Currently, I am working on a project called "hello world" and it involves two HTML pages named "configuration.html" and "add configuration.html". Each page has its own controller defined as follows: angular.module('MissionControlApp').controller ...

What ways can I leverage JavaScript to convert a provided array into multiple different arrays?

I am in need of a function that meets the following criteria: Given the dimensions of an array, return all possible combination arrays based on the given numbers. The length of the given array should be equal to the length of the array returned. The size ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

Convert to cshtml and retrieve the logged-in user's identification

I'm completely new to using AngularJS. I recently developed a demo login app, but I'm facing an issue where the page doesn't render even when the login id and password are correct. Code: app.controller('MainCtrl', ['$scope&ap ...

Attempting to extract the text within a table row cell by clicking on the cell directly following it

I am trying to extract the data from a table row when I click on a specific div within that row HTML: <td class="ms-cellstyle ms-vb2">10</td> <td class="ms-cellstyle ms-vb2"> <div class="ms-chkmark-container"> <div ...

How can I access a property of the model controller when I need to use the ngModel controller?

Implementing ng-repeat and defining a model with it resembles the code snippet below: <div ng-repeat="thing in things" ng-model="thing" my-directive> {{thing.name}} </div> Subsequently, within my directive, the structure typically appear ...

Exploring the world of n-dimensional relationships

Exploring methods to determine the neighbors of a cell within an n-dimensional space, similar to concepts like 8-connected or 26-connected cells, while accommodating any dimensionality provided in an n-tuple. Identifying adjacent neighbors is straightforw ...

Looking to retrieve country, state, city, and area based on inputting a pincode value using Node.js?

I'm currently working on a web project with nodeJs and ejs. I am looking for a solution that can automatically update the country, state, city, and area fields based on the input of a pin-code (zip-code). Are there any recommended packages in node js ...

What are the steps to retrieve raw messages from Gmail using Node.js?

I'm attempting to retrieve the complete email message data, including body content, using the raw format option specified in the gmail api reference. Unfortunately, it doesn't appear to be functioning correctly. Here is the code I'm using: ...

Save JSON data in an HTML document or vice versa

Hey there, the title of this post might seem a bit unclear but I couldn't think of another way to phrase it. So here's the dilemma: I have some data that is JSON encoded and stored in a .json file: {"foo":"bar", "bar":"foo", "far":"boo"} Additi ...

Error message: Unspecified service injected

I am currently working with 2 separate javascript files for my project. One is being used as a controller, while the other serves as a service. However, when I attempt to inject the service into the controller and access its function, an error message pops ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Dropdown selection in Angular 4 with Firebase integration

I'm currently using Angular 4 in conjunction with Firebase to create a dropdown selector for a list of properties. Upon selecting a property from the dropdown menu, I expect the location of that property to be displayed in another input field below. ...