Combining objects in Angular Javascript by merging arrays

How can I merge matching objects from 2 array objects in Angular JS?

Array 1:

[
    {"id":1,"name":"Adam"},
    {"id":2,"name":"Smith"},
    {"id":3,"name":"Eve"},
    {"id":4,"name":"Gary"},
]

Array 2:

[
    {"id":1,"name":"Adam", "checked":true},
    {"id":3,"name":"Eve", "checked":true},
]

Desired Resulting Array:

[
    {"id":1,"name":"Adam", "checked":true},
    {"id":2,"name":"Smith"},
    {"id":3,"name":"Eve", "checked":true},
    {"id":4,"name":"Gary"},
]

Is there a way to achieve this without a foreach loop?

I've attempted to use angular.merge and angular.extend but they overlap the first 2 objects instead of merging them based on matching data. Any guidance would be appreciated.

Answer №1

It's uncertain if AngularJS supports this type of merge. I've created a code snippet that achieves the same result:

function mergeArrays(array1, array2) {
    var ids = [];
    var mergedObjects = [];

    array1.map(function(element) {
        if (!(ids.indexOf(element.id) > -1)) {
            ids.push(element.id);
            mergedObjects.push(element);
        }
    });

    array2.map(function(element) {
    var index = ids.indexOf(element.id);
        if (!( index > -1)) {
            ids.push(element.id);
            mergedObjects.push(element);
        } else {
            mergedObjects[index] = element;
        }
    });

    console.log(mergedObjects);
}

var array1 = [{
    "id": 1,
    "name": "Adam"
}, {
    "id": 2,
    "name": "Smith"
}, {
    "id": 3,
    "name": "Eve"
}, {
    "id": 4,
    "name": "Gary"
}]

var array2 = [{
    "id": 1,
    "name": "Adam",
    "checked": true
}, {
    "id": 3,
    "name": "Eve",
    "checked": true
}];

mergeArrays(array1, array2);

Answer №2

Essentially, when using extend in Angular, it typically works with objects rather than arrays. However, there is a workaround available for your specific situation. Here is an alternative solution:

// a1, a2 represent your arrays
// Convert arrays to objects with id as key and array item as value
var a1_ = a1.reduce(function(obj, value) {
    obj[value.id] = value;
    return obj;
}, {});
var a2_ = a2.reduce(function(obj, value) {
    obj[value.id] = value;
    return obj;
}, {});
// Utilize extend with the two converted objects
var result = angular.extend([], a1_, a2_).splice(1)

Important Points:

  • Keep in mind, the functionality of reduce may not be supported in all cases.
  • It is crucial to note that the subsequent array will overwrite the original one due to how extend is implemented in Angular.

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

Troubles encountered when loading an Angular JS website using an Android Webview

Greetings everyone! I've been attempting to load GTV onto an Android WebView. It's working perfectly on the mobile browser, but for some reason, it's not loading in the webview. Here is my code snippet: WebView theWebPage = new WebView(t ...

Can we switch the country name to the database name in Jvector?

I've successfully implemented the Jvectormap application and it's functioning as expected. When I click on a country, it displays the name of that country. I have established a simple database for specific countries. Through AJAX, I've conn ...

The collection-repeat feature in Ionic seems to be having trouble displaying in the specified location

I have successfully developed an application, but I am facing difficulties in displaying a collection-repeat feature. Other functionalities within the app are working perfectly fine. ShowDetails.html <ion-view view-title="Parts Listing"> <ion ...

Adjusting the slide display in angular-slick based on the window's width automatically

I am new to working with Angular and I'm trying to create a responsive slideshow using angular-slick. Here is an example of my code: <slick infinite="true" slides-to-show="4" slides-to-scroll="1" prev-arrow=".slick-prev" next-arrow=".slick-next"&g ...

Determining if a value is an Object Literal in JavaScript: Tips for judging

As someone with limited experience in object type judgment, I find myself unsure of how to determine if a value is an Object Literal in JavaScript. Despite my efforts to search online for answers, I have not been successful. Any guidance or ideas on how to ...

Discovering similarities among array elements by looping through an array

Two sets of arrays have values obtained using the data-attribute(data-product-name). One set contains the full list of available items, while the other set consists of selected items associated with a country. <!-- the item list --> <div ...

Replacing all backslashes with forward slashes cannot be done using just one quotation mark; the process involves changing each ""

Struggling to switch all backward slashes with forward slashes " from \ to / . Experimented with numerous possibilities but without success. var a = 'images\1572714983295\10423479\401891269961412\82824649\n.jpg'; ...

Angular version 1.6 with ES6, no errors in the application

Can you help me understand this? Note: I am using ui-router, and I suspect that is the issue. $stateProvider .state('login',{ url:'/', /*controller:'loginController',*/ controller: function(){aler ...

Trying to locate the biggest value within an array is causing some issues

Create a program that takes a series of integers as input, stores them in an array, and then sorts the integers by using a function called selection_sort. The selection_sort function should perform the following actions when given an array with n elements: ...

Manipulate the inner HTML of a ul element by targeting its li and a child elements using JQuery

Here is the HTML code I am working with: <ul class="links main-menu"> <li class="menu-385 active-trail first active"><a class="active" title="" href="/caribootrunk/">HOME</a></li> <li class="menu-386 active"> ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

a guide on using ajax to distribute retrieved data among various td elements

After the user presses a button, the data is saved into the database. Upon success, I need to retrieve the data from the database and place it in the appropriate td (in the same row as the clicked td). I've been able to successfully retrieve the data, ...

I have a collection of emails stored as a string that I would like to convert into a json or javascript object and store in a mongodb

After selecting multiple user emails, I receive the following data: "participants" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294b5b404847695d41405b4d5b465c5d4c074a4644">[email protected]</a>,<a href="/ ...

Stop the continuous AJAX loop or look for an alternative method to retrieve and compare a list of HTML pages

I am in need of a solution to insert a small script onto all of my website pages. The script must include the correct token for each of the 21 different domains I have. However, not all the sites are directly under the 'domain name' but are consi ...

How does one distinguish between the uses of "any" and "any[ ]"?

Exploring the Difference Between any and any[ ] An Illustrative Example (Functioning as Expected) variable1: any; variable2: any[]; this.variable1 = this.variable2; Another Example (Also Functioning as Intended) variable1: any; v ...

Guide on clicking an element within a hidden iframe using Python Selenium

I am facing a challenge in finding elements within an iframe tag. Surprisingly, the HTML source does not contain any iframe tags. However, upon inspecting the element, I can see that there is indeed an iframe tag present. How can I tackle this issue using ...

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

What is the reason behind VueJS animations only functioning in a single direction?

I'm completely baffled by this issue. It seems that Vue3 is able to apply the move animation class correctly for a <transition-group/> when there is a list of items, but this only happens if the list is moved forward. I've created a CodePen ...