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

如何在ES6的map方法结果中去除空对象?

如何仅通过ES6 map方法去除结果中的空对象?

先明确一个关键点:map的核心是把数组里每个元素转成新值,原数组有多少个元素,map返回的新数组就有多少个元素——它没法跳过任何元素,所以严格来说,单靠map做不到“移除空对象”这种过滤操作,过滤是filter的职责。

不过既然你想基于map摸索解决方案,下面给你两种思路:

思路1:返回undefined替代空对象

修改map的回调逻辑,条件不满足时返回undefined,而不是空对象:

const fruits = [{
    apple: 'red',
    banana: 1
  },
  {
    apple: 'green',
    banana: 1
  },
  {
    apple: 'yellow',
    banana: 3
  }
]

const newArray = fruits.map(e => 
  e.banana === 1 ? { apple: e.apple } : undefined
)

console.log(newArray)
// 输出: [ { apple: 'red' }, { apple: 'green' }, undefined ]

但这样结果里还是有undefined,因为map必须保证数组长度和原数组一致,没法真正删掉这个位置的元素。

思路2:用flatMap间接实现(基于map的扩展)

如果想让结果直接没有无效项,可以用flatMap——它是map加扁平化的组合,当条件不满足时返回空数组,flatMap会自动把空数组“消掉”:

const newArray = fruits.flatMap(e => 
  e.banana === 1 ? [{ apple: e.apple }] : []
)

console.log(newArray)
// 输出: [ { apple: 'red' }, { apple: 'green' } ]

不过flatMap不算纯map,但它是基于map的扩展方法,勉强符合你想围绕map解决的需求。

你的原代码为啥会出空对象?

看你写的:

({ ...e.banana === 1 ? { apple: e.apple } : [] })

条件不满足时,你展开了空数组[]到对象里,空数组展开后不会给对象加任何属性,所以就得到了空对象{}。哪怕换成undefined,展开到对象里也还是空对象,因为undefined展开后不会产生任何键值对。

最后说句实在的

如果真要实现“转换+过滤”,最合理的写法还是map加filter组合,这才是符合JS方法职责划分的用法:

const newArray = fruits
  .map(e => e.banana === 1 ? { apple: e.apple } : null)
  .filter(item => item !== null)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:45:32