Home >Web Front-end >JS Tutorial >How to merge two arrays of objects in JavaScript using Array.prototype.push.apply()?

How to merge two arrays of objects in JavaScript using Array.prototype.push.apply()?

Barbara Streisand
Barbara StreisandOriginal
2024-12-22 22:37:13433browse

How to merge two arrays of objects in JavaScript using Array.prototype.push.apply()?

Merging Two Arrays of Objects: A JavaScript Solution

Merging arrays of objects in JavaScript can be a common task. Here, we explore a simple yet efficient method for achieving this using the intrinsic function Array.prototype.push.apply().

Consider the example scenario:

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

Our goal is to merge these two arrays into a single array, called arr3, with the following content:

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

Using jQuery's $.extend() is not suitable here, as it does not provide the desired output. Instead, we employ the following code:

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

console.log(arr1);

This code essentially appends the elements of arr2 to the end of arr1. The result is a single array containing the merged objects, with duplicate "lang" objects being replaced by the latter value.

The output obtained is:

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

This output matches the desired array arr3, effectively merging the original two arrays of objects.

The above is the detailed content of How to merge two arrays of objects in JavaScript using Array.prototype.push.apply()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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