简体   繁体   English

使用 javascript 或 Jquery 过滤 JSON GraphQL 数据

[英]Filter JSON GraphQL data with javascript or Jquery

I have some data pulled through the GraphQL API and stringified in JSON.我通过 GraphQL API 提取了一些数据并在 JSON 中进行了字符串化。 It looks like this看起来像这样

var data = {
"data": {
    "shop": {
        "products": {
            "edges": [{
                    "node": {
                        "title": "Green Silk T-Shirt",
                        "material": {
                            "value": "Silk"
                        }
                    }
                },
                {
                    "node": {
                        "title": "Red Silk T-Shirt",
                        "material": {
                            "value": "Silk"
                        }
                    }
                },
                {
                    "node": {
                        "title": "Blue Cotton T Shirt",
                        "material": {
                            "value": "Cotton"
                        }
                    }
                },
                {
                    "node": {
                        "title": "Red Cotton T-Shirt",
                        "material": {
                            "value": "Cotton"
                        }
                    }
                },
                {
                    "node": {
                        "title": "Pink Cotton T-Shirt",
                        "material": {
                            "value": "Cotton"
                        }
                    }
                }
            ]
        }
    }
}

} }

I also have 2 elements like so:我也有 2 个像这样的元素:

<div id="cotton"></div>
<div id="silk"></div>

I wish to use javascript (or JQuery) to loop through the JSON data and show the title of every node with a material value of "Silk" in the with the ID of silk and similarly for "cotton".我希望使用 javascript(或 JQuery)来循环遍历 JSON 数据,并显示每个节点的标题,其材料值为“Silk”,ID 为丝绸,“棉花”类似。

I understand that I can achieve this with the filter function, but I'm having issues grabbing values of one branch on the basis of the values of a lower branch.我知道我可以使用过滤器功能来实现这一点,但是我在根据较低分支的值获取一个分支的值时遇到了问题。

Is it therefore possible to do this and if so how?因此,是否有可能做到这一点,如果可以,如何做到?

I would use map for this since you dont want to return filtered nodes, but instead return the titles of each我会为此使用地图,因为您不想返回过滤的节点,而是返回每个节点的标题

var nodes = data.data.shop.products.edges;

var silks = nodes.map(node => {
    if node.material.value === 'Silk':
        return node.title
})

var cotton = nodes.map(node => {
    if node.material.value === 'Cotton':
        return node.title
})

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

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