如何通过从具有相同名称的键一起添加数值来$ .extend 2个对象?

muu*_*ess 6 javascript jquery

我目前有2个obj并使用jquery扩展函数,但是它会覆盖具有相同名称的键的值.如何将值一起添加?

var obj1 = {
  "orange": 2,
  "apple": 1,
  "grape": 1
};

var obj2 = {
  "orange": 5,
  "apple": 1,
  "banana": 1
};

mergedObj = $.extend({}, obj1, obj2);

var printObj = typeof JSON != "undefined" ? JSON.stringify : function (obj) {
  var arr = [];

  $.each(obj, function (key, val) {
    var next = key + ": ";
    next += $.isPlainObject(val) ? printObj(val) : val;
    arr.push(next);
  });

  return "{ " + arr.join(", ") + " }";
};

console.log('all together: ' + printObj(mergedObj));
Run Code Online (Sandbox Code Playgroud)

我明白了 obj1 = {"orange":5,"apple":1, "grape":1, "banana":1}

我需要的是 obj1 = {"orange":7,"apple":2, "grape":1, "banana":1}

elc*_*nrs 5

所有$.extend这一切都是加入两个对象,但它不会添加值,它会覆盖它们.您将不得不手动执行此操作.$.extend将水果添加或修改到您的对象将是有用的,但如果您需要总和,您将不得不循环:

var obj1 = { orange: 2, apple: 1, grape: 1 };
var obj2 = { orange: 5, apple: 1, banana: 1 };
var result = $.extend({}, obj1, obj2);
for (var o in result) {
  result[o] = (obj1[o] || 0) + (obj2[o] || 0);
}
console.log(result); //=> { orange: 7, apple: 2, grape: 1, banana: 1 }
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/elclanrs/emGyb/