2

我刚刚开始使用 Underscore.js,希望能得到一些关于如何执行以下操作的建议。我有以下 JSON 已被解析并存储在 parsedJson 变量中:

{
    "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,
            }
        }
    }
}

我想要实现的是将 animation.frames 值(如果存在)设置为 frames 属性中的帧数。

因此,dirt.animation.frames 的值应设置为
4。grass.animation.frames 的值应设置为 2。

我知道要计算 n 对象中的属性数量,我可以使用 _size() 但我应该如何遍历对象中的每个名称并设置 animation.speed 值(如果存在)。该对象也是动态的,因此可以包含任意数量的名称。

感谢您的帮助,答案将使我朝着正确的方向了解如何使用 underscore.js。

注意:我正在使用 CoffeeScript

4

1 回答 1

6

JS,不是 CS,而是:

_.each(obj.name,function(val){
    if('animation' in val && 'frames' in val.animation) {
        val.animation.frames = _.size(val.frames);
    }
});
于 2013-02-16T03:44:46.213 回答