-4

I want to add two JSON objects which have structure like this (It has more data and I ignore them in here):

{ "total_count":100 , "types":20 , { "a" : 5 , "b" : 6 }}

{"total_count" : 1 , { "a" : 2 } }

I want to add these objects in node.js in order to get following object:

 { "total_count":101 , "types":20 , { "a" : 7 , "b" : 6 }}

I use mongodb which has $inc function which add current json to existing one in db and reduce load and store load. I'm interested to find a method which handle this action in nodejs.What should I do ( I dont want to do it manually preferly. instead i like to use existing functions)?

JGC
  • 12,737
  • 9
  • 35
  • 57
  • 1
    I suggest writing some recursive function that adds all the values together. You'll need `for(var i in object)` syntax. – Tomáš Zato May 18 '14 at 11:45
  • Well this isn't a duplicate IMO, since the OP does not just want to merge two objects blindly together, but wants to do some transformation on the data itself, so a tailored function would make much more sense. The OP should add more details, eg whether that is a generic request or for that specific problem with that specific object-properties. – Zim84 May 18 '14 at 11:50

1 Answers1

0

something like this? your json structure is not quite correct, so i added x.

object1 = {"total_count":100 , "types":20 , "x": { "a" : 5 , "b" : 6 }};

object2 = {"total_count" : 1 , "x":{ "a" : 2 } };

object1.total_count += object2.total_count;
object1.x.a += object2.x.a;
Axil
  • 3,606
  • 10
  • 62
  • 136