Home > Web Front-end > JS Tutorial > How Can I Merge Two Arrays of Objects in JavaScript?

How Can I Merge Two Arrays of Objects in JavaScript?

Patricia Arquette
Release: 2024-11-21 08:24:10
Original
870 people have browsed it

How Can I Merge Two Arrays of Objects in JavaScript?

Merging Arrays of Objects: A JavaScript Approach

Consider the following scenario: you have an array of objects called arr1 and an array of objects called arr2, and you want to merge them into a new array arr3 that contains the elements from both arrays. A straightforward solution is to use the Array.prototype.push.apply() method.

This method takes two arguments: the first is the target array you want to add to, and the second is the array of elements you want to add. In this case, the target array is arr1 and the array of elements to add is arr2.

Here's an example:

var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

Array.prototype.push.apply(arr1,arr2); 

console.log(arr1);  
Copy after login

Output:

[{"name":"lang","value":"English"},
{"name":"age","value":"18"},
{"name":"childs","value":"5"},
{"name":"lang","value":"German"}]
Copy after login

As you can see from the output, the two arrays have been successfully merged into a single array. This method is simple and effective, and it works in both JavaScript and jQuery.

The above is the detailed content of How Can I Merge Two Arrays of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template