仅获取JSON对象

时间:2018-01-08 12:49:40

标签: javascript json

我需要弄清楚如何只抓取下面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"
 }
]

目的是能够遍历记录并仅显示涉及某些国家的记录。我希望这是一个特定的问题。

2 个答案:

答案 0 :(得分:1)

使用Array.prototype.filter方法。

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)

您可以使用Array.prototype.filter()

过滤原始数组

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)