首頁 > web前端 > js教程 > 主體

如何有效合併兩個 JavaScript 物件陣列?

Linda Hamilton
發布: 2024-11-15 09:09:02
原創
190 人瀏覽過

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" },
];
登入後複製

You want to merge these arrays into a single array:

var arr3 = [
  { name: "lang", value: "German" },
  { name: "age", value: "18" },
  { name: "childs", value: "5" },
];
登入後複製

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"}]
登入後複製

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);
登入後複製

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
登入後複製

Output:

[
  { name: "lang", value: "English" },
  { name: "age", value: "18" },
  { name: "childs", value: "5" },
  { name: "lang", value: "German" },
]
登入後複製

以上是如何有效合併兩個 JavaScript 物件陣列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板