为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Smart猫小萌 2022-10-21 14:47:57
我知道如果我有一个这样的数组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" })但是,我试图让每个具有“坐标”对象的对象都被过滤或推送到一个新数组中,以便只留下具有“坐标”对象的对象。有谁知道如何实现这一目标?
查看完整描述

3 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

我认为你只需要这样做,检查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)


查看完整回答
反对 回复 2022-10-21
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您可以根据坐标值进行过滤,如下所示。


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);


查看完整回答
反对 回复 2022-10-21
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

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。


查看完整回答
反对 回复 2022-10-21
  • 3 回答
  • 0 关注
  • 187 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号