Underscore.js - Iterating over an object and counting object properties

underscore.js

Solution

JS, not CS, but:

_.each(obj.name,function(val){
    if('animation' in val && 'frames' in val.animation) {
        val.animation.frames = _.size(val.frames);
    }
});

Problem

I have just started to use Underscore.js and would appreciate some advise on how to do the following. I have the following JSON that has been parsed and stored in parsedJson variable: ``` { "name": { "cinema": { "size": { "w": 256, "h": 200 }, "frame": { "x": 0, "y": 0, "w": 256, "h": 200 } }, "dirt": { "size": { "w": 128, "h": 64 }, "animaton": { "frames": 0, "speed": 0 }, "frames": { "frame1": { "x": 128, }, "frame2": { "x": 128, }, "frame3": { "x": 128, }, "frame4": { "x": 128, } } }, "grass": { "size": { "w": 128, "h": 64 }, "animaton": { "frames": 0, "speed": 0 }, "frames": { "frame1": { "x": 0, }, "frame2": { "x": 0, } } }, "icecream": { "size": { "w": 128, "h": 110 }, "frame": { "x": 128, } }, "tree": { "size": { "w": 128, "h": 110 }, "frame": { "x": 0, } } } } ``` What I want to achieve is to set the animation.frames value (if it exists) to the number of frames in the frames property. So the dirt.animation.frames value should be set to 4. and the grass.animation.frames value should be set to 2. I understand that to count the number of properties in n object I can use _size() but how should I go about iterating through each name in the object and setting the animation.speed value, if it exists. This object is also dynamic so can have an arbitrary number of names in it. Thanks for your help, the answer will kick start me in the right direction on how to use underscore.js. Note: I am using CoffeeScript

Original source