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

时间:2021-07-21 20:23:52

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?

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

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

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

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

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

4 个解决方案

#1


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:

所有$ .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 }

Demo: http://jsfiddle.net/elclanrs/emGyb/

#2


4  

Working Demo

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

这不是.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;
}

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.

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

#3


0  

No fancy stuff, just simple Javascript:

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

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

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

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

#4


0  

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}

#1


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:

所有$ .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 }

Demo: http://jsfiddle.net/elclanrs/emGyb/

#2


4  

Working Demo

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

这不是.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;
}

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.

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

#3


0  

No fancy stuff, just simple Javascript:

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

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

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

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

#4


0  

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}