Transfer the value of an item from one array of objects to a different array

Looking to transfer values from one array to another based on matching IDs.

array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}]

array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}]

Previous attempts at merging resulted in duplicate objects.

Desired final array structure:

array1 = [{id:1, location: 'A', value: 123},{id:2, location: 'B', value: 5466},{id:3, location: 'C', value: 89484},{id:4, location: 'D', value: -4.215}]

Answer №1

One way to iterate through an array is by utilizing the base array with the help of Array.prototype.map(). You can also incorporate Array.prototype.find() to search for matching values in another array based on their id:

const array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}],
      array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}],
      
      result = array1.map(o => ({...o, ...array2.find(_o => _o.id == o.id)}))
      
console.log(result)
.as-console-wrapper{min-height:100%;}

Answer №2

Check out the code snippet below:

var data1 = [{id:1, name: 'John'},{id:2, name: 'Jane'},{id:3, name: 'Alice'},{id:4, name: 'Bob'}]

var data2 = [{id:1, age: 25},{id:2, age: 30},{id:3, age: 28},{id:4, age: 21}]

var result = data1.map(item => {
  return {
        ...data2.filter(item2 => item2.id === item.id)[0],
        ...item
   }
})

console.log(result)

Answer №3

Here is a potential solution:

Using the map method to create a new array by merging objects from two arrays based on matching IDs.

Answer №4

In the case where the indexes are the same, you can merge and spread the objects as shown below

const array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}];

const array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}];

const merged = array1.map((a,i)=>({...a, ...array2[i]}));
 
console.log(merged); 

If the indexes do not match, you can use the following approach

const array1 = [{id:1, location: 'A'},{id:2, location: 'B'},{id:3, location: 'C'},{id:4, location: 'D'}];

const array2 = [{id:1, value: 123},{id:2, value: 5466},{id:3, value: 89484},{id:4, value: -4.215}];
  
const merged = array1.map(a=>({...a, ...array2.find(a2=>a2.id==a.id)}));

console.log(merged);

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

Converting a date array element into a PHP array variable

One of the challenges I faced was having a datepicker element in my HTML code for multiple dates generated from a database loop. The datepicker displayed fine, allowing users to choose different dates for different products. However, when it came time to ...

The update function for colors in Three.js is not being triggered when colorsNeed

I'm attempting to change the color of a face on an external event - button click. Despite searching for solutions, none have been successful so far. I have an interactive model that I want to be able to toggle its colors. The model is rendered and co ...

Creating a dropdown menu in Semantic UI React that includes icons with images

I'm looking for help with using a local jpg image instead of an icon on a Dropdown object in Semantic UI React. Can anyone provide guidance on how to achieve this? You can view the dropdown I'm currently using and how it functions without an ico ...

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

Formatting date and time in Google Chart

I am trying to utilize the Google Chart API to create a line chart. I need to retrieve data through an AJAX method and then set this data to the chart using a JavaScript JSON array. However, I am encountering difficulties with the datetime format within th ...

Encountering an issue when attempting to submit a form using ajax technology

While submitting a post method form, I encountered an issue where the input fields values were not being received upon submission. When using an Ajax call in jQuery to serialize and submit the form values, everything works correctly. However, when attempti ...

How can I ensure my game or website fits perfectly on the screen without any need

I have recently developed a fun Erase-A-Man game that is optimized for mobile devices. However, I am facing an issue where users need to scroll to view all the letters on their screens. My goal is to make the game fit perfectly on all phone screen sizes so ...

Maintaining the selected radio button based on previous input with the use of jQuery or PHP

I am in the process of developing an online quiz system. I am fetching questions and options from getquestion.php through ajax on quiz.html. On this page, I've included next and previous buttons so that users can navigate through the quiz. However, I& ...

Bypass/exclude table row

Currently, I am in the process of calculating the average of a column within a table. However, before I proceed with this calculation, I need to filter out rows that contain a particular value, specifically 'Gender = 0'. In my attempts to calcul ...

modify input type in Reactjs based on boolean state dynamically

I am currently working on implementing a checkbox feature that allows users to toggle between viewing their password or keeping it hidden. I decided to use Material UI React for the user interface elements. The checkbox is set up and functioning properly. ...

Data binding in Vue does not function properly within functional components

Clicking the button will cause the number n to increase, but the UI will display it as constant 1. <script> let n = 1 function add() { console.log(n) return ++n } export default { functional: true, render(h, ctx) { return (<div> ...

Leverage jscript and controller actions in MVC ASP.net to effectively insert new data into the database

I am looking to store data in a database from my MVC ASP.net project without the need to refresh the view page. My approach involves creating a string, sending it to the controller, and then pushing it to the database. I have already developed a function f ...

Using VueJS to dynamically manipulate URL parameters with v-model

Hello, I am new to coding. I am working on calling an API where I need to adjust parts of the querystring for different results. To explain briefly: <template> <div> <input type="text" v-model="param" /> ...

After making a selection from the list, I would like to automatically close the select menu

<div class="topnav__menu"> <button class=" topnav__button topnav__button--has-arrow topnav__menu-button " type="button" id="hideselectOptio ...

Tips for updating an ASP.NET MVC page when the browser back button is pressed

Have you ever encountered the issue where clicking the browser back button on any ASP .NET MVC page does nothing, and the page does not update unless you hit F5 to refresh it? It seems that the main problem lies in making changes to the DOM of the page, s ...

The innovative voting system powered by jQuery

Currently, I am in the process of creating a voting system that involves Thumbs Up and Thumbs Down options. My tech stack includes CakePHP, jQuery, and MySQL. However, before finalizing the front end, I want to ensure that it is done correctly and efficien ...

What is the mechanism behind shadows in THREE.js version 75?

Currently, I am exploring a tutorial on Three.js that introduces the concept of shadows, which can be implemented using methods like castShadow, receiveShadow, and enabling shadowMap. However, the example code provided is for Three.js r69, while the lates ...

Slice or eliminate the PlaneGeometry using XY coordinates

Just starting out in learning Three.js and looking to achieve the following: const customPlaneGeometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); if(customPlaneGeometry.x > 2 && customPlaneGeometr ...

Instead of constantly updating my stateful component, I prefer to create a new paragraph for each new state

Each time the Create Sales Order Button is clicked, an API call is made and the response is printed as a Stateful Component. Rather than updating the existing component, I want to generate a new paragraph for each response received so that if the user clic ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...