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

ES6通过嵌套map加过滤提取数组中isMain为true的properties元素

ES6实现方案

最简推荐写法

使用flatMap+filter组合,写法简洁易读,是日常开发的最优选择:

const result = market.flatMap(item => item.properties)
  .filter(product => product.isMain)

逻辑说明

  • flatMap会先遍历原market数组,把每个元素嵌套的properties数组合并展开为一维的商品数组
  • filter直接筛选出isMain为true的商品对象,输出结果和预期完全一致

极致性能写法

如果要减少遍历次数,也可以用reduce实现单次遍历完成筛选,适合处理超大量级的数据场景:

const result = market.reduce((res, item) => {
  item.properties.forEach(product => {
    product.isMain && res.push(product)
  })
  return res
}, [])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:30:00