简体   繁体   English

使用JavaScript遍历JSON-查找具有某些父值的子级

[英]Traversing json with javascript - finding children with certain parent values

JSON: JSON:

{resources:
    [
    {type:sound, content:0},
    {type:movie, content:1},
    {type:image, content:2},
    ...
]}

How do i most effeciently get the content of objects with type=image? 我如何最有效地获取type = image对象的内容? can i avoid having to loop through the objects? 我可以避免必须遍历对象吗?

Coming from a background working with xml i am used to working with queries inside the getter. 来自使用xml的背景,我习惯于使用getter内部的查询。

The above sample in xml would let me get the content of the image object by simply writing resources.object(type == "image").content 上面的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>

You can use lodash for this. 您可以为此使用lodash

In your case the solution would look like this - 在您的情况下,解决方案如下所示:

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

In vanilla javascript you can use filter to filter them and map to get an array of the contents: 在香草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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM