Home > Web Front-end > JS Tutorial > body text

How to Merge Two Arrays of Objects in JavaScript?

Susan Sarandon
Release: 2024-11-17 13:45:02
Original
898 people have browsed it

How to Merge Two Arrays of Objects in JavaScript?

Merge Two Arrays of Objects in JavaScript

In JavaScript, combining two arrays of objects into a single array can be easily accomplished using a simple built-in method.

To merge arrays arr1 and arr2 as described in the example, follow these steps:

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);
Copy after login

The Array.prototype.push.append method appends all elements from arr2 to the end of arr1. This results in a new merged array, stored in arr1.

Utilizing this method, you can easily consolidate arrays of objects in JavaScript. No additional libraries or jQuery functions are required.

Here's a modified version of the example with the result displayed:

console.log(arr1); // Output: [{"name":"lang","value":"English"},
// {"name":"age","value":"18"},
// {"name":"childs","value":"5"},
// {"name":"lang","value":"German"}]
Copy after login

This merge operation provides a seamless way to combine multiple data sources into a comprehensive array of objects, eliminating the need for manual looping and object construction.

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

source:php.cn
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