javascript - How to Sum two or more JSON object into One - Stack Overflow

hi i have following JSON objects;var obj1 = {"a":1,"b":1,"c":1};var obj2

hi i have following JSON objects;

var obj1 = {"a":1,"b":1,"c":1};
var obj2 = {"a":2,"b":2,"c":2};
var obj3 = {"a":3,"b":3,"c":3};

i want to sum,or subtract above 3 json Objects i want final result as

  {"a":6,"b":6,"c":6}

i know it is very simple by using different types of loop. but i want to know whether is there any function exists in javascript to merge multiple JSON objects and add or subtract each properties(without loop).

is there possible like reduce function in array: like below:

var squares = arr.concat(arr2).reduce((t,n)=>t+n);

Thanks

hi i have following JSON objects;

var obj1 = {"a":1,"b":1,"c":1};
var obj2 = {"a":2,"b":2,"c":2};
var obj3 = {"a":3,"b":3,"c":3};

i want to sum,or subtract above 3 json Objects i want final result as

  {"a":6,"b":6,"c":6}

i know it is very simple by using different types of loop. but i want to know whether is there any function exists in javascript to merge multiple JSON objects and add or subtract each properties(without loop).

is there possible like reduce function in array: like below:

var squares = arr.concat(arr2).reduce((t,n)=>t+n);

Thanks

Share Improve this question edited Nov 28, 2018 at 11:09 cнŝdk 32.2k7 gold badges60 silver badges80 bronze badges asked Nov 28, 2018 at 10:58 ghanshyam.miranighanshyam.mirani 3,11111 gold badges49 silver badges86 bronze badges 3
  • 5 ,'c'=1} is invalid syntax... – CertainPerformance Commented Nov 28, 2018 at 10:59
  • invalid syntax! – mahradbt Commented Nov 28, 2018 at 11:00
  • 1 this is just example of json object having key value pair – ghanshyam.mirani Commented Nov 28, 2018 at 11:01
Add a ment  | 

2 Answers 2

Reset to default 6

There's no such built-in function that can acplish something like that automatically, but it's trivial to write your own code that does what you want:

var obj1 = {"a":1,"b":1,'c':1};
var obj2 = {"a":2,"b":2,'c':2};
var obj3 = {"a":3,"b":3,'c':3};
const bined = [obj1, obj2, obj3].reduce((a, obj) => {
  Object.entries(obj).forEach(([key, val]) => {
    a[key] = (a[key] || 0) + val;
  });
  return a;
});
console.log(bined);

You can just loop over one of your object properties and construct the result:

let res = {};
for (p in obj1) {
  res[p] = obj1[p] + (obj2[p] || 0) + (obj3[p] || 0);
}

Demo:

var obj1 = {"a":1,"b":1,"c":1};
var obj2 = {"a":2,"b":2,"c":2};
var obj3 = {"a":3,"b":3,"c":3};

let res = {};

for (p in obj1) {
  res[p] = obj1[p] + (obj2[p] || 0) + (obj3[p] || 0);
}
console.log(res);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745089678a4610617.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信