What is the most efficient way to add a new object to an array in JavaScript by searching for a specific object in a separate array and returning a distinct object

Looking to merge two JavaScript object arrays similar to a vlookup function in Excel. The goal is to match objects from one array with another, and then combine them into a single array for streamlined access.

For instance,

    let array1 = [
        {"first":"Ana","last":"Anderson","id":"0001"},
        {"first":"Bob","last":"Brown","id":"0002"},
        {"first":"Charlie","last":"Clark","id":"0003"},
        {"first":"Danielle","last":"Dunn","id":"0004"}
    ]

    let array2 = [
        {"age":"38","id":"0002","eyeColor":"hazel","hieght":"5.5"},
        {"age":"45","id":"0001","eyeColor":"brown","hieght":"5"},
        {"age":"23","id":"0003","eyeColor":"blue","hieght":"6"}
    ]

How can I create an array that merges the data like this?

let array3 = [
        {"first":"Ana","last":"Anderson","id":"0001","age":"45","eyeColor":"brown","height":"5"},
        {"first":"Bob","last":"Brown","id":"0002","age":"38","eyeColor":"hazel","height":"5.5"},
        {"first":"Charlie","last":"Clark","id":"0003","age":"23","eyeColor":"blue","height":"6"},
        {"first":"Danielle","last":"Dunn","id":"0004","age":"","eyeColor":"","height":""}
    ]

Answer №1

  1. Create an empty object as a placeholder for no matches
  2. Map all new objects from array2 based on their ids
  3. Loop through array1 and update items using the mapped values or the empty object

let array1 = [
    {"first":"Anna","last":"Adams","id":"0005"},
    {"first":"Ben","last":"Barker","id":"0006"},
    {"first":"Cara","last":"Collins","id":"0007"}
]

let array2 = [
    {"age":"28","id":"0007","eyeColor":"green","height":"6.1"},
    {"age":"33","id":"0005","eyeColor":"blue","height":"5.8"},
    {"age":"40","id":"0006","eyeColor":"brown","height":"5.9"}
];

const blankObject = Object.keys(array2[0]).reduce((result, key) => (key !== 'id' && (result[key] = ''), result), {});
const mapping = array2.reduce((result, item) => (result[item.id] = item, result), {});
array1.forEach(item => Object.assign(item, mapping[item.id] ?? blankObject));

console.log(array1);

Answer №2

Employ a loop to cycle through array1 and match the id of each element in array1 with objects in array2 to combine the data.

let array1 = [
    {"first":"Ana","last":"Anderson","id":"0001"},
    {"first":"Bob","last":"Brown","id":"0002"},
    {"first":"Charlie","last":"Clark","id":"0003"},
    {"first":"Danielle","last":"Dunn","id":"0004"}
];

let array2 = [
    {"age":"38","id":"0002","eyeColor":"hazel","hieght":"5.5"},
    {"age":"45","id":"0001","eyeColor":"brown","hieght":"5"},
    {"age":"23","id":"0003","eyeColor":"blue","hieght":"6"}
];

let array3 = [];

for (let i = 0; i < array1.length; i++) {
    let matchedObject = array2.find(obj => obj.id === array1[i].id) || {};
  
    let mergedObject = { ...array1[i], ...matchedObject };
    
    array3.push(mergedObject);
}

console.log(array3);

Answer №3

Instead of utilizing the index values, it is more advantageous to create a Map and utilize the id as the key. Proceed to iterate through the second object, comparing the id with the map's key. If there is a match, you can then append those properties from the second array to the corresponding object in the first array.

let array1 = [{
    "first": "Ana",
    "last": "Anderson",
    "id": "0001"
  },
  {
    "first": "Bob",
    "last": "Brown",
    "id": "0002"
  },
  {
    "first": "Charlie",
    "last": "Clark",
    "id": "0003"
  },
  {
    "first": "Danielle",
    "last": "Dunn",
    "id": "0004"
  }
]

let array2 = [{
    "age": "38",
    "id": "0002",
    "eyeColor": "hazel",
    "height": "5.5"
  },
  {
    "age": "45",
    "id": "0001",
    "eyeColor": "brown",
    "height": "5"
  },
  {
    "age": "23",
    "id": "0003",
    "eyeColor": "blue",
    "height": "6"
  }
];
// initiate a new map object
const map1 = new Map();
//iterate through each element in the array and store the value in the map
array1.forEach(item => {
  map1.set(item.id, item)
});
// iterate through elements in array2 and verify if they exist in map1, if so then update 
// the object by combining the properties from both arrays
array2.forEach(item => {
  map1.has(item.id) && map1.set(item.id, { ...map1.get(item.id),
    ...item
  })

});
console.log(Array.from(map1.values()))

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

Why is my Javascript for-loop returning "null" instead of the expected value?

Having trouble with the function below that is supposed to calculate the average of all elements in array1. Unfortunately, the function keeps returning null as the result. I can't seem to pinpoint the issue. var array1 = [46,73,-18,0,-442,779,5,1400] ...

Incorporating server-side rendered components into a Vue.js parent component

I have a server-side rendered page that includes information about "orders" and a root Vue object initialized as the "parent object." Is it feasible to assign the rendered HTML orders as children of that parent Vue object? Vue.js is known for its dynamic ...

Using Vue.js 3 composition, I have encountered an issue where the v-if directive is not functioning as expected on two separate div

Is there a way to seamlessly toggle sections of the app in Vue.js 3 composition using v-if? I managed to make it work with the vue.js 2 API option initially, but since transitioning to vue.js 3 API Composition, the section isn't hiding despite screenM ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

JavaScript: Implementing a seamless spinning effect for an image [Compass needle]

I have been working on developing a compass app for mobile devices and have successfully created a function that returns the change-values for the compass-needle rotation (e.g. 20). However, I have noticed that setting the 'image-transform' to &a ...

Exploring Various Keys and Values within a PHP Array

Looking at this PHP array: Array ( [Album Title 1] => Array ( [Track Title 1] => 27 [Track Title 2] => 18 [Track Title 3] => 7 ) [Album Title 2] => Array ( [Tr ...

Get rid of any unnecessary class on the element

I'm currently working on an image slider that displays before and after images when the user drags left to right. The issue I'm facing is that the 'draggable' class is being added not only to these images but also to my hero images. It ...

Place a new button at the bottom of the react-bootstrap-typeahead dropdown menu for additional functionality

Currently, I have successfully implemented the React Bootstrap Typeahead with the desired options which is a good start. Now, my next challenge is to integrate a custom button at the end of the dropdown list for performing a specific action that is not ne ...

Convert the string into HTML bullet point elements with <li> tags

Is there a way to break down a string and extract individual words from it? I want the output to be displayed like this with <li></li> elements: -Ryan Gosling -Emma Stone -Amiée Conn -Terry Walters However, currently it is all displaying i ...

Launch pop-up window when the button is pressed

After successfully configuring the modal windows using Bootstrap and JQuery code along with certain values, a common query arises. The main question revolves around how to trigger the opening of this modal window upon pressing the process button? <butt ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

Is it possible to caution users before refreshing the page, while still allowing them to

I have a script that displays a warning message to the user when they attempt to refresh the page. It works perfectly for that purpose. However, my issue is that this same alert pops up when a user clicks on a button or a link within the website itself. I ...

Node.js meets Blockly for a dynamic programming experience

Can anyone help me figure out how to run blockly on Node.js and have the code execute directly on the server without having to save the XML first and then run it in the background? I've attempted to use various npm modules but haven't found one t ...

What is the best method for dividing strings in javascript?

After invoking a JavaScript function, I received the following results: (1, 00), (2, 10), (3, 01), (4, 11) I am looking to store this data in an array or JSON format like this: [{id:1, number: 00},{id:2, number: 10},{id:3, number: 01},{id:4, number: 11} ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

Tips for accessing the next sequential tag that is similar in HTML with the help of jQuery

I have generated the following HTML code from some plugins. <div class="parent"> <span>item1</span> <input type="hidden"></input> <span>item2</span> <span class="active">item3</span> <inpu ...

Is there a way to check for broken images in Selenium IDE?

While browsing through a website, I came across an interesting example on how to test for broken images using javascript. The only catch was that the example provided was in Ruby language. However, it got me thinking - could I potentially use the runScript ...

Sorting through a collection by using a nested array

I've been working on optimizing my code to prevent making new http requests to my API every time I need to filter results. Currently, I have an array called pageContent that is populated with data from an API fetch when the page loads. Each object in ...

Guide to efficiently populating a self-referential Mongoose model

My goal is to populate data across multiple levels using the fields from an Article model: comments: [ { type: Schema.Types.ObjectId, ref: "Comment" } ] and also from ...

Is there a way to accomplish this task with the HighCharts library?

Being new to Highcharts, I am currently working on a dashboard where I aim to showcase the percentage usage of equipment at a specific Plant. Despite reviewing various demos provided by Highcharts, I have not come across a similar example. This is the spe ...