JSON:
{resources:
[
{type:sound, content:0},
{type:movie, content:1},
{type:image, content:2},
...
]}
如何最有效地获取type = image的对象内容?我可以避免不得不遍历对象吗?
来自使用xml的后台我习惯于在getter中处理查询。
上面的xml示例让我通过简单地编写resources.object(type ==“image”)来获取图像对象的内容.content
<resources>
<object type="sound">
<content>0</content>
</object>
<object type="movie">
<content>1</content>
</object>
<object type="image">
<content>2</content>
</object>
...
</resources>
答案 0 :(得分:1)
答案 1 :(得分:1)
在vanilla javascript中,您可以使用filter
过滤它们,并map
获取内容数组:
let json = {resources:
[
{type:"sound", content:0},
{type:"movie", content:1},
{type:"image", content:2}
]};
json.resources.filter( r => r.type === "image" ).map( r => r.content)