在特定对象(Javascript)的对象数组中进行筛选
我知道如果我有一个这样的数组在特定对象(Javascript)的对象数组中进行筛选,javascript,arrays,object,Javascript,Arrays,Object,我知道如果我有一个这样的数组 locations = [ { name: 'location 1', id: '1', coordinates: {long: '', lat: ''} }, { name: 'location 2', id: '2', coordinates: {long: '', lat''} }, ]; 我可以按姓名(或id)筛选出: 但是,我试图将每个具有“坐标”对象
locations = [
{
name: 'location 1',
id: '1',
coordinates: {long: '', lat: ''}
},
{
name: 'location 2',
id: '2',
coordinates: {long: '', lat''}
},
];
我可以按姓名(或id)筛选出:
但是,我试图将每个具有“坐标”对象的对象过滤或推送到一个新数组中,以便只剩下具有“坐标”对象的对象。有人知道如何做到这一点吗
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。我认为您只需要执行此操作,检查
坐标。由于filter
会返回一个新数组,因此不需要将其推入另一个数组
var位置=[
{
名称:“位置1”,
id:'1',
坐标:{long:'',lat:'}
},
{
名称:“位置2”,
id:'2',
坐标:{long:'',lat:'}
},
{
名称:“位置3”,
id:'3',
},
];
var res=locations.filter((location)=>location.coordinates);
console.log(res)
您可以根据cordinates值进行过滤,如下所示
let locations=[{name:'location 1',id:'1',坐标:{long:'lat:'}},{name:'location 2',id:'2',坐标:{long:'lat:'}];
让坐标=位置.过滤器(l=>!!l.坐标);
控制台日志(坐标)代码>在过滤函数中:返回位置。hasOwnProperty(“坐标”)
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);