Updating array content based on property criteria

I've been tackling a project in Angular where I have two arrays set up like this:

array1 = [
  {
    Name: "Jack",
    Id: "1",
    Location: "UK"
  },
  {
    Name: "Rose",
    Id: "2",
    Location: "USA"
  },
  {
    Name: "Mary",
    Id: "3",
    Location: "India"
  }
];

array2 = [
  {
    Name: "Raj",
    Id: "5",
    Location: "UK"
  },
  {
    Name: "John",
    Id: "2",
    Location: "Germany"
  },
  {
    Name: "Maria",
    Id: "3",
    Location: "Canada"
  }
];

I'm looking to create a new array where if the "Id" of any element in array1 matches an "Id" from array2, then the data for that specific "Id" should be replaced in array2. The resulting array would look like this:

resultArray = [
  {
    Name: "Raj",
    Id: "5",
    Location: "UK"
  },
  {
    Name: "Rose",
    Id: "2",
    Location: "USA"
  },
  {
    Name: "Mary",
    Id: "3",
    Location: "India"
  }
];

In this case, the Id values 2 and 3 from array1 matched with those in array2, so the corresponding data in array2 was replaced by that of array1. Any ideas on how I can achieve this?

Answer №1

To solve this problem, you can utilize the map and find functions. By adding an OR condition, you can check if a certain value is present in array1. If it is found, the object from array1 will be selected; otherwise, the current object will be chosen.

var array2=[ { "Name": "Peter", "Id": "5", "Location": "Spain" }, { "Name": "Lisa", "Id": "2", "Location": "France" }, { "Name": "Michael", "Id": "3", "Location": "Australia" }];

var array1= [{ "Name": "Tom", "Id": "1", "Location": "Japan"},{ "Name": "Sarah", "Id": "2", "Location": "Brazil"},{ "Name": "Alex", "Id": "3", "Location": "Mexico"}];

var result = array2.map(p=>(array1.find(k=>k.Id==p.Id) || p));

console.log(result);

I trust that this explanation has been beneficial to you.

Answer №2

You can achieve your goal by using the reduce and find functions.

array2.reduce((acc, c) => {
  var existed = array1.find(a=>a.Id == c.Id);
  if(existed){
     c.Name = existed.Name;
  }
  return c;
}, [])

var array1= [
{
   "Name": "Jack",
   "Id": "1",
   "Location": "UK"
},
{
   "Name": "Rose",
   "Id": "2",
    "Location": "USA"
},
{
   "Name": "Mary",
   "Id": "3",
   "Location": "India"
}
]

var array2=[
 {
       "Name": "Raj",
       "Id": "5",
       "Location": "UK"
    },
    {
       "Name": "John",
       "Id": "2",
        "Location": "Germany"
    },
    {
       "Name": "Maria",
       "Id": "3",
       "Location": "Canada"
    }
];


array2.reduce((acc, c) => {
  var existed = array1.find(a=>a.Id == c.Id);
  if(existed){
     c.Name = existed.Name;
  }
  return c;
}, [])

console.log(array2)

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 user's input is not being accurately represented when making an AJAX request to the

When attempting to incorporate a user's city input (e.g. Los Angeles) into Ajax URL parameters, there seems to be an issue where the '+' is not being added between "los angels", resulting in a broken URL when console.log(searchURL) is used. ...

How can I convert duplicate code into a function in JavaScript?

I have successfully bound values to a view in my code, but I am concerned about the duplicate nested forEach loops that are currently present. I anticipate that Sonarcube will flag this as redundant code. Can anyone advise me on how to refactor this to avo ...

A solitary outcome yielded by the JSON iteration

Can anyone help me understand why this code is only returning 1 result instead of 4? I am trying to retrieve all the post titles in the category with ID 121, but it seems to only display the most recent post title. <script type="text/javascript> ...

Tips for incorporating a CSS transition when closing a details tag:

After reviewing these two questions: How To Add CSS3 Transition With HTML5 details/summary tag reveal? How to make <'details'> drop down on mouse hover Here's a new question for you! Issue I am trying to create an animation when t ...

Trigger functions by clicking or bind click events by calling a function?

I need help comparing two similar code snippets: myFunc(); function myFunc() { var e = document.getElementByClassName("link"), i = e.length; while (i--) { e[i].addEventListener("click", function() { //do stuff for each ...

Skipping an item in an array during the filtering process

I encountered an issue while trying to filter an array using a specific method. However, I noticed that one value is being skipped in the process! function customFilterArray(array, remove){ console.log('Length of Array:',array.length) ...

Issue: The Material-UI DataGrid Column Filter is not compatible with Material-UI Dialog

I am currently facing an issue with my Material-UI DataGrid in React JS. I have successfully integrated the table inside a Material-UI DialogContent and everything seems to be working fine - ordering, renderCells, checkboxSelection, etc. However, I am enco ...

Implementing Voting Functionality with Ajax Submission

Can anyone help me with getting ajax functionality to work properly for my Acts_As_Votable buttons? Here's the current code I have: post_controller.rb def favorite @post = Post.find(params[:id]) @post.upvote_from current_user respond_to do |f ...

jQuery Files in Conflict

The issue I am facing involves the code below. The first function requires linked js and css, while the second one needs a jQuery and javascript file inherited from base.html. However, there seems to be a conflict in loading these files (possibly because o ...

Managing numerous API requests in React Native

As I work on implementing a search field, I've encountered a challenge. Whenever a user enters text in the search field, a timer resets to 300 ms before an API call is sent to fetch autocomplete results. After receiving these results, the app then wai ...

Error: The function referenced is not defined when the page loads

Trying to incorporate two different script tags in a single HTML page has been quite a task for me. The first script tag contains the location of a JS file that I need to use for a specific function, while the second script tag is where I have written anot ...

Tips for matching the width of tooltips with the length of the title

I am trying to adjust the width of the antd tooltip to match that of the title. Here is the code snippet: <Tooltip placement="top" align={{ offset: [0, 10] }} title='this is the title'> <span>tooltip</span> </T ...

How do I create a generic function in TypeScript that adjusts its behavior based on the input argument?

Is there a way to create a generic function that can accept generic arguments like Data<string, number>? Take a look at this code snippet: interface Data<T,R> { a:T; c:R; } function foo( data: Data<string, number> ){ return t ...

Incorporate JSON information into HTML dropdown menu using Google API

I'm finding it difficult with this task. Below is a list that needs the name and address inserted into the dropdown menu from the JSON file. <div class="dropdown-list"> <div class="list-container"> <ul class="list" ...

How can I use vanilla JavaScript to retrieve all elements within the body tag while excluding a specific div and its descendants?

My goal is to identify all elements within the body tag, except for one specific element with a class of "hidden" and its children. Here is the variable that stores all elements in the body: allTagsInBody = document.body.getElementsByTagName('*&apos ...

Exploring ThreeJS by Casting Rays on HTML Elements

We are currently encountering an issue with ThreeJS. Our goal is to integrate HTML elements into ThreeJS and use raycasting to determine whether we are pointing to any HTML element. However, when we intersect with it, it returns an empty array. An example ...

"Implement a feature to populate dropdown options in an Angular select component with retrieved

I'm currently utilizing ngx-select-dropdown (https://github.com/manishjanky/ngx-select-dropdown) and my goal is to fetch a list of Cities in an array of objects to display them in a select menu dropdown autocomplete. However, I'm encountering dif ...

Using jQuery to Capture Datepicker Input and Assigning to PHP Variable

I need help figuring out how to save a jQuery datepicker value in a php date formatted variable. My goal is to have: input field named "reviewdate" = 03/02/2015 input field named "reviewmonth" = 3 Both values should be stored in a mysql database. I am ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Issues with Fetch API and CORS in Web Browsers

Hello, I'm encountering an issue related to CORS and the Fetch API when using browsers. Currently, my setup involves running a NodeJS server built with Express on localhost:5000. This server responds to a GET request made to the URL /get_a, serving ...