我目前有 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));
我得到obj1 = {"orange":5,"apple":1, "grape":1, "banana":1}
我需要的是 obj1 = {"orange":7,"apple":2, "grape":1, "banana":1}