Home > Web Front-end > JS Tutorial > How to Efficiently Merge Two JavaScript Arrays of Objects?

How to Efficiently Merge Two JavaScript Arrays of Objects?

Linda Hamilton
Release: 2024-11-15 09:09:02
Original
265 people have browsed it

How to Efficiently Merge Two JavaScript Arrays of Objects?

Merging Arrays of Objects in JavaScript

Suppose you have two arrays of objects:

var arr1 = [
  { name: "lang", value: "English" },
  { name: "age", value: "18" },
];

var arr2 = [
  { name: "childs", value: "5" },
  { name: "lang", value: "German" },
];
Copy after login

You want to merge these arrays into a single array:

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

jQuery's $.extend() Method

You may initially consider using $.extend(). However, it does not meet your requirements, as it simply updates the first array:

$.extend(arr1, arr2); // arr4 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}]
Copy after login

Using Array.prototype.push.apply()

A more effective way to merge the arrays is to use Array.prototype.push.apply():

Array.prototype.push.apply(arr1, arr2);
Copy after login

This line of code essentially pushes the elements of arr2 onto the end of arr1. The result is a merged array stored in arr1.

// 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); // final merged result will be in arr1
Copy after login

Output:

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

The above is the detailed content of How to Efficiently Merge Two JavaScript Arrays of Objects?. 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