繁体   English   中英

如何过滤再次包含 JSON 对象数组的 JSON 对象数组?

[英]How can i filter an array of JSON objects which again contain an array of JSON objects?

我想从示例 json 对象中获取名称,其中 workLocation 是“city 1”,我该怎么做?

我知道我们可以使用下划线或 lodash 过滤 json 对象数组,例如 var filtersData = _.where(jsonData,{"id": 1}) 但不确定如何从特定的工作位置获取名称?

[
{
    "id": 1,
    "name": "John",
    "age": 12,
    "data": [
        {
            "worklocation" : "city 1",
            "pin" : "909"
        },
        {
            "worklocation" : "city 2",
            "pin" : "808"
        }
    ]
},
{
    "id": 2,
    "name": "Shawn",
    "age": 22,
    "data": [
        {
            "worklocation" : "city 3",
            "pin" : "608"
        },
        {
            "worklocation" : "city 4",
            "pin" : "508"
        }
    ]
}
]

当我使用 city 3 过滤时,我期望 { "name" : "Shawn"} 的输出

你必须遍历两个数组和比较,如果有可能找到worklocation用相同的ID。 我为你创建了一个例子。

 const data = [ { "id": 1, "name": "John", "age": 12, "data": [{ "worklocation": "city 1", "pin": "909" }, { "worklocation": "city 2", "pin": "808" } ] }, { "id": 2, "name": "Shawn", "age": 22, "data": [{ "worklocation": "city 3", "pin": "608" }, { "worklocation": "city 4", "pin": "508" } ] } ] const findName = (list, id) => { const found = list.find(item => { const foundCity = item.data.find(worklocationItem => worklocationItem.worklocation === id) return !!foundCity }) if (found) { return found.name } return null } const el = document.getElementById('data') const cityID = 'city 3'; el.innerHTML = findName(data, cityID) console.log(findName(data, cityID))
 <div id="data"></div>

暂无
暂无

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

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