我需要弄清楚如何只抓取下面json对象的某些记录。例如,只有名字叫西班牙的人。
我做了一些研究,但我读过的内容对我来说没什么意义。
var trips = [
{
"name": "Spain",
"visit_id": 1,
"city": "Barcelona",
"year": 2016,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},{
"name": "Spain",
"visit_id": 2,
"city": "Moraira",
"year": 2015,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "Portugal",
"visit_id": 1,
"city": "Lisbon",
"year": 2016,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "Italy",
"visit_id": 1,
"city": "Rome",
"year": 2017,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "France",
"visit_id": 1,
"city": "Paris",
"year": 2015,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
}
]
目的是能够遍历记录并仅显示涉及某些国家的记录。我希望这是一个特定的问题。
答案 0 :(得分:1)
const trips = [
{
"name": "Spain",
"visit_id": 1,
"city": "Barcelona",
"year": 2016,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},{
"name": "Spain",
"visit_id": 2,
"city": "Moraira",
"year": 2015,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "Portugal",
"visit_id": 1,
"city": "Lisbon",
"year": 2016,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "Italy",
"visit_id": 1,
"city": "Rome",
"year": 2017,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "France",
"visit_id": 1,
"city": "Paris",
"year": 2015,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
}
];
const result = trips.filter(el => el.name === 'Spain');
console.log(result);
无论如何,这个解决方案在某些旧版本的浏览器中不起作用,因为它使用的是filter
和胖箭头(=>
),它们是ECMAScript2015(ES6)的功能。
答案 1 :(得分:1)
var trips = [
{
"name": "Spain",
"visit_id": 1,
"city": "Barcelona",
"year": 2016,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},{
"name": "Spain",
"visit_id": 2,
"city": "Moraira",
"year": 2015,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "Portugal",
"visit_id": 1,
"city": "Lisbon",
"year": 2016,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "Italy",
"visit_id": 1,
"city": "Rome",
"year": 2017,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
},
{
"name": "France",
"visit_id": 1,
"city": "Paris",
"year": 2015,
"main_img": "main.jpg",
"other_imgs": "001.jpg, 002.jpg"
}
]
var filtered = trips.filter(function(val){
return val.name == 'Spain';
})
console.log(filtered)