Searching an array object inside another array object using JavaScript/AngularJS

Here is my issue:

I am facing a situation where I have two Array objects as follows

var array1 = [{ "id": 1, "name": "potatoe", photo="photo"}, {"id": 2, "name": "budget"}]

var array2 =  [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": 
 "UhOhAnotherName"}, {"id": 2, "name": "budget"}]

My goal is to search if the ID object in array1 exists in array 2. If it does, I want to replace the name value. If it doesn't exist, like with id 3, I want to add it.

The expected result would be

[{ "id": 1, "name": "potatoeModified", photo="photo"}, {"id": 2, "name": "budget"},
{ "id": 3, "name": "UhOhAnotherName"}]

I have attempted to achieve this, but each time I end up with a function that has too high of a cyclomatic complexity. I do not want one massive function for this task. I believe the solution is straightforward, yet I seem to be missing something... Thank you :)

Answer №1

Here is a solution to try:

var array1 = [{ "id": 1, "name": "potatoe", "photo":"photo"}, {"id": 2, "name": "budget"}];

var array2 =  [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": 
 "UhOhAnotherName"}, {"id": 2, "name": "budget"}];

array1.map(function(val,i){
  array2.forEach(function(v){
    if(val.id == v.id){
      val.name = v.name;
    }
    else{
      var found = array1.some(function (el) {
        return el.id === v.id;
      });
      if (!found) { array1.push(v); }
    }
  })
  
  return val;   
});

console.log(array1);

Answer №2

To efficiently merge two arrays, you can create temporary objects using the id's as keys to store each item.

Then, iterate through the second array's temporary object and either update the name or add it to the first array based on whether the id key exists in the first temporary object.

var array1 = [{ "id": 1, "name": "potatoe", photo:"photo"}, {"id": 2, "name": "budget"}];
var array2 =  [{ "id": 1, "name": "potatoeModified"},{ "id": 3, "name": 
 "UhOhAnotherName"}, {"id": 2, "name": "budget"}];
 
// Create temporary objects using a helper function below
var tmp_1 = toObj(array1), 
    tmp_2 = toObj(array2);


// Iterate through array 2 temporary object and either adjust name or push to array 1
Object.keys(tmp_2).forEach((key)=>{       
   if(tmp_1[key]){
     // Update name if the same id exists from array one
     tmp_1[key].name = tmp_2[key].name;
   }else{
     // Add to array one when the same id doesn't exist
     array1.push(tmp_2[key]);
   }
});

console.log(array1);
 
// Helper function to avoid code duplication
function toObj(arr){
   return arr.reduce((a,c)=>{
     a[c.id] = c;
     return a;
   },{})
}

There are different approaches like using Array.prototype.find() or nested loops to achieve this, but creating hashmap objects is efficient for merging arrays.

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

Issue with the initial selection of <select> element in Internet Explorer

When utilizing the ng-options directive with a select element in Internet Explorer, we're encountering some unusual behavior that doesn't occur when using <option ng-repeat=''>. After selecting an option from the drop down box cr ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

How to extract cookie value in a node.js application using socket.io

How can I retrieve cookie values in a node server using socket.io? Whenever a socket sends a message to the server, I need to check the value of the cookie. However, I only want to obtain the cookie value and not the session cookie as done in Express. r ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

What is causing the 'Invalid Hook Call' error to appear in React?

I have recently started learning React and I am currently working on converting a functional component into a class component. However, I encountered an error message that says: Error: Invalid hook call. Hooks can only be called inside of the body of a fu ...

Location of Custom HTML Widget in Django-Dashing

I've encountered a dilemma while using the Django-Dashing framework, specifically regarding the placement of my HTML file for a custom widget. I have meticulously configured the code in my dashboard.html file to ensure proper loading. {% extends &apo ...

Javascript does not have the capability to interact directly with HTML code

I am facing an issue with my JSP code that is supposed to validate password and confirm password before submitting the form to a Java servlet. The problem is, even though I have written the validation script, it does not show alert messages or focus on t ...

Steer clear of retrieving all the elements from the HTML DOM at once

Scenario I am working on a HTML5+CSS+JS slideshow project that needs to be synchronized across 50 clients in a local area network using a single wireless router. Challenge Due to the heavy content, particularly images, of the slides, I intend to dynamic ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

Challenges in achieving two-way data binding with directives, controllers, and services

My mind is preoccupied with a particular issue at the moment. There is a service responsible for managing logo panels and a function used for navigating between these panels. When the getPanels function is called, it sets the currentPanel, index, and leng ...

Using jQuery, you can create and add an element to the page when a user clicks

Currently, my webpage contains numerous anchor tags that link to various video files, along with a single div element: <a href="http://www.example.com/example-1.mkv" class="video">1</a> <a href="http://www.example.com/example-2.mkv" class=" ...

Tips for safely storing JWT tokens in a react/next.js app:

After a valid user login following proper registration through REST API, I am looking for the best way to store the JWT token that is generated. I have researched various methods of storing JWT on the client side, including local storage, session storage, ...

Is it possible to add items to a JS object that isn't an array?

Here is an example of the object I am working with: { "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0 } } To access this data in my JavaScript code, I use a $.getJSON call. ...

Encountering unexpected behavior with the .data() method

I'm encountering an issue with my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv= ...

Which is quicker when utilizing jQuery selectors: selecting by .classname or div.classname?

Which is quicker: using $(".classname"). or adding the tag to search for as well? $("div.classname") In my opinion, using just the classname would be faster because jQuery can simply loop through all classnames directly, whereas in the second example i ...

Combining Two Validation Methods for jQuery Validate Plugin

Seeking advice on how to incorporate custom validation methods from jQuery validate into another method for validating data. Specifically, I have a 'Document ID' field that can accept either CPF or CNPJ (Brazilian documents) and I need to validat ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

Create a dynamic sitemap for a Laravel website that includes variables in the slugs

My Laravel-based website features URLs like this- xyz.com/search/{id}/{name} These URLs have two variables, allowing for multiple variations such as: xyz.com/search/1/katy xyz.com/search/2/john With potentially thousands of such URLs, I need to creat ...

Setting the Node environment as an environment variable within the application: a step-by-step guide

Struggling with setting process.env.NODE_ENV to TEST in my code. Check out the relevant snippets below: test.js import server from "../../src/index.js"; process.env.NODE_ENV = "test"; console.log(process.env.NODE_ENV); // outputs &qu ...

Retrieve numerical values in inch format from a given string and output the greater value

Trying to extract size information from product names: Product A 30" Metalic Grey Product B 31.50" Led 54 watt Product C 40"-60" Dark Green The current code for fetching size information is: var product_name = $(this).text(); product_name.split('"& ...