6

我目前有 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

4 回答 4

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/

于 2012-08-31T03:22:05.863 回答
4

工作演示

不是这样的.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 个。

于 2012-08-31T03:26:17.770 回答
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}

于 2012-08-31T03:26:28.747 回答
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));
于 2012-08-31T03:29:40.807 回答