-3

Consider the following JavaScript object:

{
"moe": {
    "25-34": {
        "female": {
            "foo": 1747600,
            "bar": 0.17625997236482466
        },
        "male": {
            "foo": 1002100,
            "bar": 0.10107010660722751
        }
    },
    "18-24": {
        "female": {
            "foo": 1104200,
            "bar": 0.11136773946282867
        },
        "male": {
            "foo": 735800,
            "bar": 0.07421154020716296
        }
    }
},
"larry": {
    "18-24": {
        "male": {
            "foo": 2229400,
            "bar": 0.23708698010272988
        },
        "female": {
            "foo": 743800,
            "bar": 0.07909989046398605
        }
    },
    "25-34": {
        "male": {
            "foo": 2092200,
            "bar": 0.22249635766167197
        },
        "female": {
            "foo": 852500,
            "bar": 0.09065966203354142
        }
    },

}

I need to subtract each "bar" value of Moe from Larry, or vice versa - it does not really matter. Each "stooge" node will always have the same properties e.g. 18-24, foo, bar etc however, the number of child items (18-24 etc) will vary and therefore cannot be hard coded. The stooge names will always be different also.

Can anyone advise how I would dynamically subtract the bar values of one object to the other?

UPDATE: there will always be 2 stooges with exactly the same child properties.

Ben
  • 6,026
  • 11
  • 51
  • 72
  • What more than how to iterate over properties do you need to know? Does this help: [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/q/11922383/218196) ? – Felix Kling Mar 29 '16 at 04:36
  • Are there always just 2 stooges? – Barmar Mar 29 '16 at 04:43
  • 1
    For this you can use the `subtractMoeFromLarry` routine. Unfortunately, you would have to write it yourself. –  Mar 29 '16 at 04:44

1 Answers1

0

Use nested loops.

var names = Object.keys(json_obj);
var stooge1 = json_obj[names[0]];
var stooge2 = json_obj[names[1]];

for (var age in stooge1) {
    for (var gender in stooge1[age]) {
        stooge2[age][gender].bar -= stooge1[age][gender].bar;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • many thanks, thats really helpful. I was struggling with the fact the key names can change so using Object.keys works nicely. – Ben Mar 29 '16 at 04:59