如何过滤一个又包含JSON对象数组的JSON对象数组?

时间:2019-07-17 02:18:55

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

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

我知道我们可以使用下划线进行过滤或对json对象数组进行过滤,例如varfilteredData = _.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“}的输出

1 个答案:

答案 0 :(得分:0)

您必须迭代两个数组,并比较是否可以找到具有相同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>