【发布时间】:2018-01-09 13:42:50
【问题描述】:
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>
【问题讨论】:
-
data.resources.filter(resource => resource.type === 'image')?还应注意,您在问题中显示的 JSON 无效,因为没有引用任何字符串。 -
请注意,您使用的任何方法(包括
filter、lodash等)都在“幕后”循环。
标签: javascript json xml