最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to $.extend 2 objects by adding numerical values together from keys with the same name? - Stack Overflow

programmeradmin2浏览0评论

I currently have 2 obj and using the jquery extend function, however it's overriding value from keys with the same name. How can I add the values together instead?

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));

And I get obj1 = {"orange":5,"apple":1, "grape":1, "banana":1}

What I need is obj1 = {"orange":7,"apple":2, "grape":1, "banana":1}

I currently have 2 obj and using the jquery extend function, however it's overriding value from keys with the same name. How can I add the values together instead?

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));

And I get obj1 = {"orange":5,"apple":1, "grape":1, "banana":1}

What I need is obj1 = {"orange":7,"apple":2, "grape":1, "banana":1}

Share Improve this question edited Aug 31, 2012 at 7:10 Danil Speransky 30.5k6 gold badges69 silver badges78 bronze badges asked Aug 31, 2012 at 3:11 muudlessmuudless 7,5427 gold badges40 silver badges58 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

All $.extend does is join the two objects but it doesn't add the values, it overrides them. You're going to have to do this manually. $.extend will be useful to add or modify fruits to your object but if you need the total sum you gonna have to loop:

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 }

Demo: http://jsfiddle/elclanrs/emGyb/

Working Demo

That's not how .extend() works; you'll have to implement your own:

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;
}

Usage:

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}

Of course, like .extend(), this will work with any number of objects -- not just 2.

No fancy stuff, just simple Javascript:

The c[k] || 0 is there in the event that c[k] has no value, it gets to be zero.

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));

Here's some code you could use:

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));

Output:

{"orange":7,"apple":2,"grape":1,"banana":1}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论