You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript对象数组中筛选包含coordinates对象的元素?

筛选包含coordinates对象的数组元素

嘿,既然你已经会用filter方法筛选name或id,那这个需求对你来说简直小菜一碟,还是用filter就能解决!

核心思路就是在filter的回调函数里,判断每个元素的coordinates属性是否存在且是一个对象(避免把null或者其他非对象类型误判进去)。直接上代码:

// 假设你的原数组是locations
const locationsWithCoordinates = locations.filter(location => {
  // 先检查coordinates是否存在,再确认它是对象类型
  return location.coordinates && typeof location.coordinates === 'object';
});

为什么这么写?

  • location.coordinates会自动排除undefined、null这类“空值”的情况;
  • 加上typeof location.coordinates === 'object'是为了更严谨——比如如果某个元素的coordinates是字符串、数字这类非对象类型,我们就不会错误地把它保留下来。

如果你的数据源里coordinates要么是对象要么干脆不存在(不会出现null或者其他类型),那也可以简化成更简洁的写法:

const locationsWithCoordinates = locations.filter(location => location.coordinates);

举个实际测试的例子:

const locations = [
  { name: 'location 1', id: '1', coordinates: {long: '', lat: ''} },
  { name: 'location 2', id: '2', coordinates: {long: '', lat: ''} },
  { name: 'location 3', id: '3' }, // 无coordinates属性
  { name: 'location 4', id: '4', coordinates: null }, // coordinates为null
  { name: 'location 5', id: '5', coordinates: 'invalid' } // coordinates是字符串
];

const result = locations.filter(location => location.coordinates && typeof location.coordinates === 'object');
// 结果只会包含location 1和location 2

这样处理后,locationsWithCoordinates里就只保留了所有包含有效coordinates对象的元素啦~

内容的提问来源于stack exchange,提问作者networkcore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:22:55