【问题标题】:Traversing json with javascript - finding children with certain parent values使用 javascript 遍历 json - 查找具有某些父值的子项
【发布时间】: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 =&gt; resource.type === 'image')?还应注意,您在问题中显示的 JSON 无效,因为没有引用任何字符串。
  • 请注意,您使用的任何方法(包括filterlodash 等)都在“幕后”循环。

标签: javascript json xml


【解决方案1】:

在原版 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)

【讨论】:

  • 这看起来很完美。谢谢
【解决方案2】:

您可以为此使用lodash

在您的情况下,解决方案将如下所示 -

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多