Combining two arrays containing objects in JavaScript

Imagine having 2 arrays of objects that you want to merge in a parallel manner. For instance

var array = [{foo: 2} , {boo: 3}]
var array2 = [{foo2: 2}, {boo2: 4}]

The outcome would be

var array3 = [{foo:2,foo2:2},{boo:3,boo2:4}]

In what way can this be achieved using javascript?

Answer №1

To combine arrays, you could consider using Array.prototype.map alongside Object.assign.

array.map((object, index) => Object.assign(object,array2[index]));

Answer №2

To combine two arrays, you can iterate through one array to select an item and then select the corresponding item from the second array to merge them together.

var fruits = [{apple: 2} , {banana: 3}];
var vegetables = [{carrot: 2}, {celery: 4}];

var combinedArray = fruits.map(function(fruitObj, i){
  
  var veggieObj = vegetables[i];
  for (var attr in veggieObj) { fruitObj[attr] = veggieObj[attr]; }
  return fruitObj;

});

// combinedArray is the merged array

alert(JSON.stringify(combinedArray));

Answer №3

If you're in need of a tool to merge objects in JavaScript, consider checking out Lodash:

var users = {
  'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
};

var ages = {
  'data': [{ 'age': 36 }, { 'age': 40 }]
};

_.merge(users, ages);
// → { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }

You can find more information about Lodash's merge function here.

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

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

Automatically close an element when you click on a different element

Hello everyone! I need some help again. I'm working on a script that displays an overlay when a menu item is clicked. Within this menu, there is a modal contact form with a close icon or anchor that should appear when clicked. My goal is to have the o ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...

Is there a way to identify which specific item in a watched array has been altered in VueJS?

Imagine having an array declared in the data section like this: data() { return { myData : [{foo:2, bar:3},{foo:4,bar:5}] } } If you want to identify when the bar property of the second element changes, what should your watch function look li ...

Irritating Popup - (or perhaps a more elegant alternative)

My current challenge involves tracking the time a user spends with a specific window in focus. I aim to record this duration accurately and pause the timer when the user switches to another window, then resume it upon returning. Ultimately, I want to measu ...

Is it possible to deploy Vue.js from a content delivery network (CDN) for production

My decision to use Vue.js for a new project was influenced by its ability to run natively in the browser, unlike React which requires compilation/transpilation via Node. I'm considering linking directly to a CDN like this in my production code: <s ...

Ensure UseEffect is only triggered once with specific dependencies

Whenever the component is loaded, I have a method called useEffect() that runs once. useEffect(() => { (async function fetchData() { const results = await stateIsoAPI(); setStates(results); // API results to trigger other Use effect ...

Creating a multidimensional JSON array using PHP

I'm struggling to create a JSON array from the JQuery UI map with a specific structure. {"markers":[{"latitude":57.7973333, "longitude":12.0502107}, {"latitude":57.6969943, "longitude":11.9865}]} At this point, I'm unsure of how to achieve this ...

Acquire JSON information from PHP utilizing JavaScript

I am a beginner with JSON and I'm retrieving data from PHP code in JSON format. [ { "Title": "New Event", "TYPE": "info", "StartsAt": "16 November 201512:00", "EndsAt": "25 November 201512:00" }, { ...

Experience a login page similar to Google's with a fully functional back button

I'm currently working on a login page that requires the user to enter their username and have it validated before proceeding. Once the username is confirmed as valid, a new input field for password entry should appear. However, I'm facing an issu ...

The focus functionality in Angular seems to be malfunctioning

Having trouble with simple focus in Angular <div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();"> html <input type="text" data-ng-model="mod ...

Improving the functionality of the JavaScript key press function

I have a small javascript snippet on my website that allows me to navigate the site using the arrow keys on my keyboard. document.onkeydown = function(evt) { evt = evt || window.event; switch (evt.keyCode) { case 37: ...

Incorporate an additional retrieve functionality in your asp.net web api

I'm brand new to the world of asp.net web api. I have a solid understanding of get(), put(), post() and delete(). For my application, I need to implement two additional get() methods. Here is an overview- public class StudentController : ApiControll ...

What is the best way to select the child of the second-to-last child?

In the structure of my HTML code, I have an unordered list with a class "menu" containing several list items and corresponding anchor tags like this <ul class="menu"> <li> <a href="#1"></a> </li> <div&g ...

InnerHTML syntax for creating the button in the cell is not functioning properly with the HTML onclick event

I'm facing an issue with my code where I am trying to insert a button into a table cell. The button has an action assigned to it using the onclick attribute. However, no matter how I try to use single quotes with or without backslashes in the syntax o ...

Using the THIS keyword in JQUERY for functions without an action: a guide

Is there a way to dynamically set the widths of table elements based on their parent's data-attribute value? For example, if a parent has percent="10", I want the child element to have a width of 10%. How can this be accomplished? To illustrate, here ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Having trouble initiating NPM in a terminal

I keep encountering an issue whenever I try to start NPM using a command in the terminal. Here is the error message that appears: npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark your favorite packages npm ERR! npm stars # Vi ...

Enhancing Javascript functionality with additional on.change customization opportunities

My website currently has a dynamic AJAX script that updates a table based on the selection from a dropdown menu with the ID of [id="afl_player_ID"]. However, I am looking to extend this functionality so that the same script runs when either [id="afl_playe ...

The configuration error occurred for the `get` action due to an unexpected response. Instead of an object, an array was received

Despite numerous attempts, I am struggling to find a solution that works for me. In my Courses controller, I am using the Students service and Staff service to access my staff and student objects. My goal is to retrieve the staffs and students objects in o ...