简体   繁体   English

如何在JavaScript中合并2个对象?

[英]How can I merge 2 object in javascript?

How can I merge 2 object in javascript? 如何在JavaScript中合并2个对象? eg if objB.a2 not exist then objB.a2 = objA.a2 例如,如果objB.a2不存在,则objB.a2 = objA.a2

objA = {
  a1: 
  a2: 
  a3: 
}

objB = {
  a1:
  a3:
}
for (var k in objB) {
  if (typeof objB[k] === 'undefined') {
       // objB[k] = 
  }
}

With jQuery you can just do this: 使用jQuery,您可以执行以下操作:

$.extend(objB, objA);

This will merge all the properties of objA into objB . 这会将objA所有属性合并到objB To merge them into a whole new object do this: 要将它们合并为一个新对象,请执行以下操作:

var objC = {};
$.extend(objC, objA, objB);

Without jQuery you can do it like this (this will add objA 's properties to objB ): 如果没有jQuery,您可以这样做(将objA的属性添加到objB ):

for (var attrname in objA) { objB[attrname] = objA[attrname]; }

For more details see: How can I merge properties of two JavaScript objects dynamically? 有关更多详细信息,请参见: 如何动态合并两个JavaScript对象的属性?

Try this 尝试这个

function merge(obj1,obj2){
    var obj3 = {}, prop;
    for (prop in obj1) {
        obj3[prop] = obj1[prop];
    }
    for (prop in obj2) {
       obj3[prop] = obj2[prop];
    }
    return obj3;
}
merge(obj1, obj2);

You can use _.extend() method from Underscore.JS as well. 您也可以使用Underscore.JS中的_.extend()方法。 See details in http://underscorejs.org/#extend 查看http://underscorejs.org/#extend中的详细信息

It is a tiny and powerful JavaScript library of helper functions. 它是一个功能强大的微型JavaScript库。

If you want to receive a NEW object with properties of both objA and objB i suppose you could use a function like: 如果您想接收一个同时具有objA和objB属性的NEW对象,我想您可以使用如下函数:

objA = {
  a1: 1,
  a2: 2,
  a3: 3
}

objB = {
  a1: 4,
  a4: 5
}

function merge(objA, objB){
  var o = {};
  for (prop in objA) //copy objA props to new object
    o[prop] = objA[prop];

  for (prop in objB) { //copy objB props to new object
    if (o[prop] === undefined) //check if the property name is used already
      o[prop] = objB[prop]; // if the prop name is not used - assign it
}
  return o;
};

console.log(merge(objA, objB)); //check the result!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM