过滤特定对象的对象数组(Javascript)

我知道如果我有一个这样的数组


locations = [

    {

      name: 'location 1',

      id: '1',

      coordinates: {long: '', lat: ''}

    },

    {

      name: 'location 2',

      id: '2',

      coordinates: {long: '', lat''}

    },

];

我可以按名称(或 ID)过滤掉:


locations.filter(function(location){ return location.name === "location 1" })

但是,我试图让每个具有“坐标”对象的对象都被过滤或推送到一个新数组中,以便只留下具有“坐标”对象的对象。有谁知道如何实现这一目标?


Smart猫小萌
浏览 188回答 3
3回答

缥缈止盈

我认为你只需要这样做,检查coordinates。您不需要推入另一个数组,因为filter无论如何都会返回一个新数组。  var locations = [    {      name: 'location 1',      id: '1',      coordinates: {long: '', lat: ''}    },    {      name: 'location 2',      id: '2',      coordinates: {long: '', lat:''}    },    {      name: 'location 3',      id: '3',    },];var res =   locations.filter((location) =>  location.coordinates);console.log(res)

拉莫斯之舞

您可以根据坐标值进行过滤,如下所示。let locations = [{name: 'location 1', id: '1', coordinates: {long: '', lat: ''} }, { name: 'location 2', id: '2', coordinates: {long: '', lat:''} } ];let coordinates = locations.filter(l => !!l.coordinates);console.log(coordinates);

拉丁的传说

const locations = [    {      name: 'location 1',      id: '1',      coordinates: {long: 1, lat: 1}    },    {      name: 'location 2',      id: '2',      coordinates: {long: 2, lat: 2}    },    {      name: 'location 3',      id: '3',    },];const filterLocation = (locations) => {    let filteredLocations = []    locations.filter((location) => {         if(location.hasOwnProperty("coordinates")) {            filteredLocations.push(location)        }    })    return filteredLocations}const newLocations = filterLocation(locations);console.log('newLocations', newLocations);这将返回一个新的数组位置,其中没有位置 3。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript