我刚刚开始使用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,
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的是将animation.frames值(如果存在)设置为frames属性中的帧数.
因此,dirt.animation.frames值应设置为4.
并且grass.animation.frames值应设置为2.
我知道要计算n个对象中的属性数量,我可以使用_size(),但是如何迭代对象中的每个名称并设置animation.speed值(如果存在).此对象也是动态的,因此可以在其中包含任意数量的名称.
感谢您的帮助,答案将启动我如何使用underscore.js的正确方向.
注意:我使用的是CoffeeScript
小智 6
JS,而不是CS,但是:
_.each(obj.name,function(val){
if('animation' in val && 'frames' in val.animation) {
val.animation.frames = _.size(val.frames);
}
});
Run Code Online (Sandbox Code Playgroud)