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

时间:2012-08-31 03:11:45

标签: 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));

我得到obj1 = {"orange":5,"apple":1, "grape":1, "banana":1}

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

4 个答案:

答案 0 :(得分: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 }

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

答案 1 :(得分:4)

Working Demo

这不是.extend()的工作原理;你必须实现自己的:

function mergeObjects() {
    var mergedObj = arguments[0] || {};
    for (var i = 1; i < arguments.length; i++) {
        var obj = arguments[i];
        for (var key in obj) {
            if( obj.hasOwnProperty(key) ) {
                if( mergedObj[key] ) {
                    mergedObj[key] += obj[key];
                }
                else {
                    mergedObj[key] = obj[key];
                }
            }                
        }
    }
    return mergedObj;
}

用法:

var obj1 = { "orange": 2, "apple": 1, "grape": 1 };
var obj2 = { "orange": 5, "apple": 1, "banana": 1 };
var mergedObj = mergeObjects( obj1, obj2);
// mergedObj {"orange":7,"apple":2,"grape":1,"banana":1}

当然,像.extend()一样,这适用于任意数量的对象 - 而不仅仅是2。

答案 2 :(得分:0)

以下是您可以使用的一些代码:

obj1 = {"orange":2,"apple":1, "grape":1};
obj2 = {"orange":5,"apple":1, "banana":1};
var joined = {};

// add numbers in arr to joined
function addItems(arr) {

    // cycle through the keys in the array
    for (var x in arr) {

        // get the existing value or create it as zero, then add the new value
        joined[x] = (joined[x] || 0) + arr[x];
    }
}

addItems(obj1);
addItems(obj2);
console.log(JSON.stringify(joined));

输出:

  

{ “橙色”:7, “苹果”:2, “葡萄”:1, “香蕉”:1}

答案 3 :(得分:0)

没有花哨的东西,只是简单的Javascript:

如果c[k] || 0没有值,则会c[k],它会变为零。

var a = {orange:2, apple:1, grape:1};
var b = {orange:5, apple:1, banana:1};
var c = {};
var k;

for (k in a)  {c[k] = 0 + a[k] + (c[k] || 0)}
for (k in b)  {c[k] = 0 + b[k] + (c[k] || 0)}


window.alert(JSON.stringify(c));