访问和搜索JSON文件中的数据

时间:2017-12-24 12:47:58

标签: javascript json search

如果我有下面的JSON对象

 {
    "animals":{     
        "a_1":{    
        "species":"Tiger",     
        "name":"Timmy",     
        "dob":"2016-03-12",       
        },    
        "a_2":{    
        "species":"Lion",     
        "name":"Leo",     
        "dob":"2012-12-04",           
        }   
    }    
} 

如何搜索返回

"a_1": {    
    "species":"Tiger",     
    "name":"Timmy",     
    "dob":"2016-03-12",       
},    

搜索a_1

是否有类似的方式来调用a_1 / a_2等?

2 个答案:

答案 0 :(得分:0)

我认为您应该将数据结构更改为数组。这会更容易:

const data = {
  "animals": {
    "a_1": {
      "species": "Tiger",
      "name": "Timmy",
      "dob": "2016-03-12",
    },
    "a_2": {
      "species": "Lion",
      "name": "Leo",
      "dob": "2012-12-04",
    }
  }
}
const animalList = Object.keys(data.animals).map(key => ({
  key,
  item: data.animals[key]
}))
const searchName = input => animalList.filter(animal => animal.item.name === input);
console.log(searchName('Leo'))

答案 1 :(得分:0)

您可以直接按键搜索。

例如:

providers