按ID过滤JSON数据数组

时间:2016-12-25 17:54:40

标签: javascript json

我遇到了以id

过滤此结果的问题
 "sectors": [
{
  "id": 1,
  "slug": "pilgrimage",
  "name": "Pilgrimage",
  "city_id": "1"
},
{
  "id": 2,
  "slug": "travel-preparation",
  "name": "Travel Preparation",
  "city_id": "2"
},
{
  "id": 3,
  "slug": "the-people",
  "name": "The People",
  "city_id": "1"
}
]

我将如何通过Id

过滤此响应

1 个答案:

答案 0 :(得分:0)

我不认为我完全理解你,你想通过他获得这个数组的一个元素吗?

如果我在这里正确解决方案:

 var request = function(id){

    for(var i = 0; i < object.length; i++){
        if(object[i].id == id){
            console.log(object[i])
        }
    }
}

当你调用像request(2);这样的函数时,它们会返回你的对象......