本文介绍了合并对象(关联数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript中合并两个关联数组的最佳/标准方法是什么?每个人都只是通过滚动自己的来进行
循环吗?
What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for
loop?
推荐答案
使用jquery,您可以调用 $ .extend
with jquery you can call $.extend
var obj1 = {a: 1, b: 2};
var obj2 = {a: 4, c: 110};
var obj3 = $.extend(obj1, obj2);
obj1 == obj3 == {a: 4, b: 2, c: 110} // Pseudo JS
(关联数组是js中的对象)
(assoc. arrays are objects in js)
看这里:
编辑像rymo建议的那样,最好这样做:
edit: Like rymo suggested, it's better to do it this way:
obj3 = $.extend({}, obj1, obj2);
obj3 == {a: 4, b: 2, c: 110}
As这里obj1(和obj2)保持不变。
As here obj1 (and obj2) remain unchanged.
edit2: 2018年的做法它来自 Object.assign
:
edit2: In 2018 the way to do it is via Object.assign
:
var obj3 = Object.assign({}, obj1, obj2);
obj3 === {a: 4, b: 2, c: 110} // Pseudo JS
如果使用ES6,可以使用:
If working with ES6 this can be achieved with the Spread Operator:
const obj3 = { ...obj1, ...obj2 };
这篇关于合并对象(关联数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!