Javascript根据数组中对象的指定属性值找到对象,现有如下数组,根据ID值找到数组中对应的对象:

var geoCoords = [
{id:1,name:'北京', geoCoord:[116.46, 39.92]},
{id:2,name:'上海', geoCoord:[121.48, 31.22]},
{id:3,name:'重庆', geoCoord:[106.54, 29.59]},
{id:4,name:'天津', geoCoord:[117.2, 39.13]}
];

方法1:

var data= geoCoords.filter(function(item){
    return item.id == 3;
})
console.log(data[0]);//{id: 3, name: "重庆", geoCoord: Array(2)}

方法2:

var data= geoCoords.find((item) => {
   if(item.id == 3){
     return item
   }
})
console.log(data);////{id: 3, name: "重庆", geoCoord: Array(2)}