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

Ensure that each of the two divs maintains a 16:9 aspect ratio, and utilize one div to fill any remaining empty space through the

This layout is what I am aiming for: While I can achieve a fixed aspect ratio with a 16:9 image by setting the img width to 100%, I run into an issue where the height scaling of flexbox becomes non-responsive. The height remains constant, and only the fir ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

Tips for handling the final row of a CSV file in Node.js with fast-csv before the 'end' event is triggered

After using fast-csv npm, I noticed that in the code provided below, it processes the last row (3rd row) of CSV data only after triggering the "end" event. How can this issue be resolved? ORIGINAL OUTPUT : here processing request here processing re ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

convert and transform XML data into JSON format

I have been working with nodejs-expressjs and I received a response in raw XML format. My goal is to convert this raw XML into either a JavaScript array or a JSON array so that I can extract the domain name along with its status. I want to display this inf ...

When properties are passed and then mapped, they become undefined

While I experience no errors when directly mapping the array, passing the same array through props results in an error stating "Cannot read property 'map' of undefined." Brands Array const brands = [ { key: 1, Name: "Nike", }, { ...

DataGrid Component: Implementing a Button for Deleting Rows

I am currently developing a React component with MaterialUI, incorporating a Datagrid to manage a queue of files. The layout resembles this: One functionality I'm focusing on is when the user clicks on the three dots at the end of each row, a Menu (c ...

A regular expression in Javascript that can be used to identify at least one word starting with a number among multiple words, with a

Currently, I am utilizing JavaScript Regex to validate an input field based on specific conditions: The value must consist of only alphabets and numbers There should be a minimum of two words (more than two are allowed) Only one word can start with a num ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

How can a function in one React component be invoked from another component?

Currently in my React project's App.js, I am calling the this.searchVenues() function in my return statement. It works, but the implementation is messy and I know there must be a more efficient way to achieve this. The searchVenues() function is locat ...

Updating votes on the client side in WebForms can be achieved by following these steps

I am currently working on implementing a voting system similar to Stack Overflow's. Each item has a vote button next to it, and I have it functioning server side causing a delay in reloading the data. Here is the current flow: Clicking the vote butt ...

Designing unique variations using Material UI

I am currently exploring the creation of custom variants for the Button component in Material UI. To start off, I am developing a customized component based on the Button component with specific styles: // CTA.js import { makeStyles } from "@materia ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

The issue with AngularJS Factory values not updating across multiple views

My current approach involves a simple factory that retrieves a list of products from a database and allows users to toggle whether a product is marked as a favorite or not through user interactions. function factoryProduct($http,$filter) { var data = { ...

What is the reason for Vue not updating the component after the Pinia state is modified (when deleting an object from an Array)?

When using my deleteHandler function in pinia, I noticed an issue where the users array was not being re-rendered even though the state changed in vue devtools. Interestingly, if I modify values within the array instead of deleting an object from it, Vue ...

Disposing of memory in THREE JS when switching between routes in VUE

Currently, I am delving into the world of VUE JS and working on a basic SPA that navigates through different pages. In my spare time, I have developed several THREE JS demos which unfortunately tend to slow down and eventually halt when switching between ...

Angular does not select the variable_name within the $scope

Here is the HTML code I have written. <div class="container" ng-app="mintcart"> <div class="panel panel-default" ng-controller="categoriesctrl"> <input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/&g ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...

express-validator never accepts valid input

Currently, I am working on a project using the most recent version of nodejs and express. The basic site setup is complete, and now I am focusing on implementing user authentication based on what I've learned from this course. However, no matter what ...