Merge 2 objects in AngularJS based on property value

I am trying to merge two different object arrays based on their "id" value.

For example, if my first array is:

[
  {
   "id": "75318408571184",
   "component": "textInput",
   "index": 0,
   "label": "Text",
   "description": "description",
   "placeholder": "placeholder",
   },
  {
  "id": "9463537670672",
  "component": "textArea",
  "index": 1,
  "label": "Paragraph",
  "description": "description",
   "placeholder": "placeholder"
  }

and the second one looks like this:

[
  {
   "id": "75318408571184",
   "value": "value1"
   },
  {
  "id": "9463537670672",
  "value": "value2"
  }

I would like the result to be:

 [
  {
   "id": "75318408571184",
   "component": "textInput",
   "index": 0,
   "label": "Text",
   "description": "description",
   "placeholder": "placeholder",
   "value": "value1"
   },
  {
  "id": "9463537670672",
  "component": "textArea",
  "index": 1,
  "label": "Paragraph",
  "description": "description",
   "placeholder": "placeholder",
   "value": "value2"
  }

Is there a more efficient way to achieve this in Angular or JavaScript without iterating through the array?

Answer №1

check out this solution:

const mergedArray = firstArray.map(item => {
    const match = secondArray.find(i => item.id === i.id);
    return match ? { ...item, ...match } : item;
});
console.log(mergedArray);

Learn more about Array.prototype.map(), which transforms each element in firstArray using a provided function.

Find out how Object.assign() is used to merge properties from the second object into the item object mentioned in the code snippet above.

Answer №2

The responses provided above are excellent. However, if you're interested in exploring additional libraries, I recommend checking out this one: loadash merge

const object = {
  'fruits': ['apple'],
  'vegetables': ['beet']
};

const other = {
 'fruits': ['banana'],
 'vegetables': ['carrot']
};

_.merge(object, other, function(a, b) {
  if (_.isArray(a)) {
    return a.concat(b);
 }
});

// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }

Answer №3

If you're working with plain Javascript, you have the option to utilize Array.prototype.forEach() and Array.prototype.some()

var obj1 = [{ "id": "75318408571184", "component": "textInput", "index": 0, "label": "Text", "description": "description", "placeholder": "placeholder", }, { "id": "9463537670672", "component": "textArea", "index": 1, "label": "Paragraph", "description": "description", "placeholder": "placeholder" }],
    obj2 = [{ "id": "75318408571184", "value": "value1" }, { "id": "9463537670672", "value": "value2" }];

obj2.forEach(function (a) {
    obj1.some(function (b) {
        if (a.id === b.id) {
            b.value = a.value;
            return true;
        }
    });
});
document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');

Alternatively, you could create a hash table temp first and then directly manipulate the items.

var obj1 = [{ "id": "75318408571184", "component": "textInput", "index": 0, "label": "Text", "description": "description", "placeholder": "placeholder", }, { "id": "9463537670672", "component": "textArea", "index": 1, "label": "Paragraph", "description": "description", "placeholder": "placeholder" }],
    obj2 = [{ "id": "75318408571184", "value": "value1" }, { "id": "9463537670672", "value": "value2" }],
    temp = {};

obj1.forEach(function (a, i) {
    temp[a.id] = i;
});
obj2.forEach(function (a) {
    obj1[temp[a.id]].value = a.value;
});
document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');

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

Unable to verify the provided resource: Mailchimp

Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...

Convert the existing jQuery function to Angular 9 syntax

I have just started learning Angular and am finding it challenging to rewrite a jQuery code that I use for loading the "classycountdown" script. Below is the jQuery function that I need to convert: $(document).ready(function() { var remainingSec = $(& ...

Multi selection dropdown feature in Angular failing to populate the options

I am working on a small Angular controller that manages a dropdown menu, with the second dropdown menu populating based on the selection made in the first one. Despite my best efforts, I can't seem to populate the dropdown menus with any content from ...

Navigating back to an Angular page from a non-Angular page using Protractor

Is there a specific method to return to an angular page? Below is the input and button code from an HTML (non-angular) page: <input class="value" type="password" 3dsinput="password" name="password"> <input type="submit" value="Submit" name="submi ...

The rendering of Markdown does not work properly when using Angular's data-binding feature

I found this interesting example on a JSFiddle that I'm trying to adapt for dynamic date population in my Angular ng-repeat. The example works, but I'm having trouble with data-binding. Below is the code snippet: JavaScript .directive('mar ...

Utilizing the React hook useReducer technique

Currently exploring the useReducer React API, and curious about the variations between the theoretical (documented) approach and the one I have developed. Initial state of the component using useReducer hook: const [fields, dispatch] = React.useReducer(f ...

Guide to integrating an interactive map with Symfony: linking a popup marker to a template

I am currently working on creating an interactive map to showcase climbing sites in France. The goal is to have a popup marker that directs users to a detailed template of the site when clicked. My project is based on Symfony framework and I've been t ...

How to troubleshoot AJAX sending a null string to an MVC controller

Here is the AJAX call that I am using: addClass: "noty-btn", text: "OK", onClick: function($noty) { var applianceId = JSON.stringify(result); ...

Is "content_scripts" malfunctioning in Chrome version 38 and above?

Just recently, I created a Chrome Extension with the purpose of making all webpages utilize a specific font. Everything was functioning perfectly fine until yesterday (or possibly even earlier). The crucial codes for this extension are: manifest.json fil ...

Utilize and store images based on the individual user's preferences with PlayCanvas

Currently, I am immersed in a PlayCanvas endeavor where I am trying to render specific objects with textures of my choice. The main issue arises when I come across the config.json file in the PlayCanvas build. Within this file, there is a designated path ...

Javascript error: Function not defined

For some reason, I seem to be hitting a roadblock with this basic function. It's telling me there's a reference error because apparently "isEven" is undefined: var isEven = function(number) { if (number % 2 == 0) { return true; ...

Type in data into the database in real-time

Can someone help me with inserting data into a database while typing values in a textbox? My AJAX code doesn't seem to be working and I'm not getting any errors. Please assist me as soon as possible. Here is my AJAX code: var userid = '#u ...

The steps to building a personalized checkbox that includes an indeterminate state

I've been attempting to achieve an indeterminate state for a custom checkbox without success. My efforts using css have not yielded the desired outcome. This is what I've tried so far: $(document).ready(function() { var checkboxes = docume ...

Utilizing Vue to pinpoint the DOM element of another component: Steps for success

Upon clicking the sidebar icon in Sidebar.vue component: <i class='bx bx-menu' v-on:click="toggleMenu()" id="btn"></i> I want to toggle the classes of elements in different components: methods: { toggl ...

How to implement saving TypeScript Map() in Firebase Cloud Functions?

I am currently developing a Firebase Cloud Functions application using TypeScript that is designed to save an instance of Map() to Cloud Firestore. The map consists of user IDs as keys and objects with 2 simple attributes as values. Due to the dynamic natu ...

What is the best way to verify the accuracy of my model when it includes an array property?

One of the challenges I am facing is dealing with a class that has an array property in MVC. public class MyClass { public int Contrato_Id { get; set; } public string Contrato { get; set; } public int Torre_Id { get; set; } public string T ...

Tips for accessing array or JSON data with ReactJS

As a novice with the MERN stack, I have set up my express app to run on port 3001 with a dbconn route. When I access "localhost:3001/dbconn," it displays the docs array successfully. const mongoose = require('mongoose') const MongoClient = req ...

Is there a way to dynamically enhance a JSON child array with additional value?

I am currently working on implementing a filter system similar to the one shown in the image. This project is being developed using Angular JS framework and JQuery. The main requirement is to have checkbox filters for Application Name, Status, and so on. ...

Having difficulty capturing an error related to an invalid form body in discord.js

I built a command to send an embed based on JSON data, and it's working well for the most part. When I input the data correctly, the bot sends it to the channel as expected. However, if someone tries to insert text in a link section, it crashes the b ...

What is the best way for me to implement a .config feature to allow for customization of my

I have developed a small code library for angular js. Within my library's main module, I have implemented a method called .config that relies on my moduleConfigProvider. I anticipate the user of my library to invoke .configure on my config provider du ...