How to match and merge two arrays of objects based on a shared value in JavaScript

let array1 = [{
  "id": "lap-143240121",
  "position": 0
}, {
  "id": "lap-15040293",
  "position": 1
}, {
  "id": "lp-1504444",
  "position": 2
}, {
  "id": "lp-150440987",
  "position": 3
}]

let array2 = [{
  "id": "lap-143240121",
  "name": "name1"
}, {
  "id": "lap-15040293",
  "name": "name2"
}, {
  "id": "lp-1504444",
  "name": "name3"
}]

I want to combine these two arrays based on the id, resulting in:

let combinedArray = [{
  "id": "lap-143240121",
  "position": 0,
  "name": "name1"
}, {
  "id": "lap-15040293",
  "position": 1,
  "value": "name2"
}, {
  "id": "lp-1504444",
  "position": 2,
  "value": "name3"
}]

Answer №1

To achieve the desired result, make use of the map method to iterate over object2, followed by utilizing the rest operator to construct an object that contains all elements along with their corresponding names from object1.

const object1 = [{
  "ident": "lap-143240121",
  "ind": 0
}, {
  "ident": "lap-15040293",
  "ind": 1
}, {
  "ident": "lp-1504444",
  "ind": 2
}, {
  "ident": "lp-150440987",
  "ind": 3
}]

const object2 = [{
  "ident": "lap-143240121",
  "name": "example1"
}, {
  "ident": "lap-15040293",
  "name": "sample2"
}, {
  "ident": "lp-1504444",
  "name": "model3"
}];

const objResult = object2.map((item) => {
  return {
    ...item,
    index: object1.find(elem => elem.ident === item.ident).ind 
  }
});

console.log(objResult)

Answer №2

  • convert object1 to a Map where the value of code becomes the key and the entire object becomes the value
  • loop through object2 and check for the presence of code from object2 in the map created above, if it exists, combine the properties

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

How can I automatically choose the first element in an ng-repeat loop using AngularJS?

Do you have any thoughts on how to accomplish this task? Currently, I have set up one controller where if you click on an element, an animation appears above. However, my goal is to have the first element automatically active/clicked as soon as the page l ...

Tips for choosing the node_modules distribution flavor to include in your webpack bundle

Issue: Following the update of AJV.js to Version 6.4, my vendor bundle now includes the "uri-js" ESNEXT version instead of the ES5 version, causing compatibility issues with IE11. Analysis: Upon investigation, I discovered that AJV references uri-js usi ...

Tips for minimizing Ant Design bundle size with TypeScript in a Next.js project using Less styles

While working on my Next.js application, I observed that the file sizes are quite large during the build process. Interestingly, the size remains consistent across pages, indicating that the entire AntD package is being imported. Page ...

Having trouble with webpack displaying CSS background images?

I've set up the html boilerplate using webpack. I'm currently encountering an issue where calling an image in my scss file like "background: url('/img/img.png');" isn't working. I've included the webpack file and folder struct ...

Python Script for Determining the Local Average of Every Coordinate in a Large Matrix

I have a large 4000x4000 matrix and I need to calculate the local average of an 11x11 window for each x,y coordinate in this matrix. Typically, it would look something like this: for x in range(4000): for y in range(4000): b[x,y] = mean(a[x-5:x+5, y ...

Tips on preventing the insertion of special characters into a form field with the help of jQuery

I'm implementing a feature to restrict users from using special characters in the text input field. While I have successfully prevented users from typing these characters, I am also looking to prevent the pasting of any special characters as well. FID ...

Reformatting function transforms the structure of an array containing objects

I have been struggling with certain issues and would like to find the most effective solution. Despite using map and reduce, I have not been able to achieve the desired results. Any help would be greatly appreciated. Consider the following INPUT Array str ...

Is it possible to access the Amazon Product API through JavaScript in a Chrome Extension?

Exploring Chrome extensions has been a fun adventure for me, and one thing I am eager to do is request product information from the Amazon Product Advertising API. Although the code needed for this task seems straightforward, I have hit a roadblock - acces ...

Showing a coordinated timer countdown alongside automatic server-side logout

I found inspiration in this particular PHP session timer example that incorporates an AJAX call to monitor the session's 'time'. I aim to integrate a simple JavaScript countdown timer for the user, like so: function startTimer(duration, di ...

In order to address the issue of displaying a 404 error in In-Memory Angular,

I have watched all the videos regarding the In-memory web API and diligently followed all the steps and instructions. However, I am still encountering a 404 Error. Please inform me if I missed something or made an error. I have attempted to troubleshoot an ...

Deleting object property within Angular ng-repeat loop

I have information structured like this: $scope.cart={"4": {"cost": 802.85, "description": "test", "qty": 1}, "5": {"cost": 802.85, "description": "test", "qty": 1}}; My goal is to iterate through this data and show it with a remove button. How can I s ...

The semantic UI search functionality is malfunctioning

My experience with semantic ui involves encountering an issue where the search result on a website appears empty, despite finding the JSON result in my console. This is the JavaScript code I am using: $('.ui.search').search({ apiSettings: { ...

Tips for opening a local HTML file in Internet Explorer

Is there a way to make an HTML file saved on the desktop open in Internet Explorer instead of Chrome as the default browser? Alternatively, is it possible to set Microsoft Word hyperlinks to open website links in Internet Explorer? Thank you! ...

Issue with AngularJS $scope data binding not working properly inside an iframe element

I find myself in a foreign place.... in my home, why does this happen: Video Url: {{exercise.videos[0].url}} It works correctly by displaying the video url... but: <iframe src="http://fast.wistia.net/embed/iframe/{{exercise.videos[0].url}}"></ ...

Step-by-step guide on creating a login functionality in Node using the Mean.io stack

I'm currently working on a web app using the MEAN.io stack. I have completed the frontend part with HTML, CSS, and AngularJS along with some logic. Now, I am looking to implement server-side login functionality, but I'm unsure where to begin sinc ...

What is the best way to utilize AJAX in sending chosen files to a PHP script?

I currently have two forms set up. Form A includes fields for name, age, address, email, and a hidden text field that holds the names of images to be uploaded in form B. Form B allows users to browse and select their photos using an input type File. ...

The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation ...

The predicament with arranging arrays

I'm working with an array that looks like this: [ { "TaskID": 303, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { "TaskID": 304, ...

Looping through jQuery click() function

I used a loop to generate div elements and I am trying to modify the background-color when the div is clicked. var c = $("#container")[0]; for(var i=0; i<6; i++){ var x = document.createElement("div"); x.className = "sqare"; x.click(changecolor(t ...

Confirming the validity of an email address with Md-chips

Email Validation for MD-Chips Struggling with creating an email validation for md-chips. The current expression I'm using is not working as expected, since the ng-keypress directive is triggered every time I type something. Any suggestions on how to ...