TypeScript 如何从嵌套对象数组提取子数组值生成扁平对象数组
问题原因与解决方案
原实现失效的核心原因
你之前使用双层嵌套map无法得到目标结果,本质是map方法的固定特性:map返回的数组长度永远和调用它的原数组长度保持一致,不会自动把返回值里的嵌套数组摊平成外层数组的元素。
按照你之前的双层map写法,最终会得到带一层嵌套的数组结构:
// 双层map的实际输出 [ [{id: 1, city: {name: "BERLIN"}}], [{id: 2, city: {name: "PARIS"}}], [{id: 3, city: {name: "LONDON"}}, {id: 3, city: {name: "EXETER"}}] ]
这和你需要的一维扁平数组结构存在层级差异。
正确实现代码
针对这种“遍历数组,把每个元素对应的子数组拆成独立顶层元素”的需求,最适配的方法是flatMap:它会在遍历每个元素、执行内部map生成对应城市条目后,自动把生成的子数组展平一层,直接输出你需要的一维结构:
const sourceArr = [ { id: 1, city: [{ name: "BERLIN" }] }, { id: 2, city: [{ name: "PARIS" }] }, { id: 3, city: [{ name: "LONDON" }, { name: "EXETER" }] } ]; const targetArr = sourceArr.flatMap(item => item.city.map(cityObj => ({ id: item.id, city: cityObj })) );
代码执行后的输出完全匹配预期的目标结构:
[ { id: 1, city: { name: "BERLIN" } }, { id: 2, city: { name: "PARIS" } }, { id: 3, city: { name: "LONDON" } }, { id: 3, city: { name: "EXETER" } } ]
兼容方案
如果运行环境不支持flatMap,可以通过map后接单层flat实现完全等价的效果:
const targetArr = sourceArr .map(item => item.city.map(cityObj => ({ id: item.id, city: cityObj }))) .flat(1);
内容的提问来源于stack exchange,提问作者Heptagram
相关产品推荐
相关产品推荐

