【问题标题】:How can i filter an array of JSON objects which again contain an array of JSON objects?如何过滤再次包含 JSON 对象数组的 JSON 对象数组?
【发布时间】:2019-11-25 19:19:51
【问题描述】:

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

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

[
{
    "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"
        }
    ]
}
]

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

【问题讨论】:

    标签: arrays node.js json underscore.js lodash


    【解决方案1】:

    您必须迭代这两个数组并比较是否可以找到具有相同 ID 的 worklocation。我为您创建了一个示例。

    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>

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      相关资源
      最近更新 更多