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

JavaScript如何将含unwrap标记的嵌套数组项展开为扁平化数组?

数组展开的简洁实现方案

直接使用ES6新增的flatMap方法即可实现,它天生支持一对多的数组映射,会自动将返回的子数组扁平化一层,刚好适配你的场景:

const result = items.flatMap(item => {
  return item.unwrap ? item.items : item
})
// 简写版本
const result = items.flatMap(item => item.unwrap ? item.items : item)

如果需要兼容不支持flatMap的旧环境,也可以用reduce方法实现,逻辑同样聚合简洁:

const result = items.reduce((acc, cur) => acc.concat(cur.unwrap ? cur.items : cur), [])

注意你之前的forEach实现里误将子数组字段写为contents,你的原始结构中子数组字段为items,需要对应修改避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:39:03