使用javascript遍历json - 查找具有某些父值的子项

时间:2018-01-09 13:42:50

标签: javascript json xml

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>

2 个答案:

答案 0 :(得分:1)

您可以使用lodash

在您的情况下,解决方案看起来像这样 -

_.filter(resources, { 'type': 'image' });

答案 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)
相关问题