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

TypeScript如何合并对象数组中的嵌套data数组

在TypeScript中合并对象数组内的嵌套数组

这需求太常见啦,给你分享几个在TypeScript里好用的实现方式,都是简单易懂的:

方法一:用flatMap(最简洁)

flatMap可以说是为这种场景量身定做的——它先对数组元素做映射,再自动把结果扁平化一层,完美匹配你的需求:

const res = [ { data: [1,2,3] }, { data: [4,5,6] } ];
const mergedArray = res.flatMap(item => item.data);
console.log(mergedArray); // 输出: [1,2,3,4,5,6]

这个方法一行代码就搞定,可读性拉满,而且TypeScript会自动推导mergedArray的类型为number[],不用额外声明。

方法二:用reduce(更灵活)

如果你需要在合并过程中做一些额外处理(比如过滤某些元素),reduce会是更灵活的选择:

const res = [ { data: [1,2,3] }, { data: [4,5,6] } ];
const mergedArray = res.reduce((accumulator, currentItem) => {
  // 这里可以加额外逻辑,比如过滤掉大于5的元素:
  // const filteredData = currentItem.data.filter(num => num <=5);
  // return accumulator.concat(filteredData);
  return accumulator.concat(currentItem.data);
}, []); // 初始化累加器为空数组

console.log(mergedArray); // 输出: [1,2,3,4,5,6]

方法三:用forEach(最直白)

如果你偏爱更直观的循环写法,forEach搭配扩展运算符也能轻松实现:

const res = [ { data: [1,2,3] }, { data: [4,5,6] } ];
const mergedArray: number[] = [];

res.forEach(item => {
  mergedArray.push(...item.data);
});

console.log(mergedArray); // 输出: [1,2,3,4,5,6]

这种写法逻辑一目了然,适合刚接触数组操作的朋友理解。

这些方法在TypeScript里都能完美运行,毕竟TS是JS的超集,原生数组方法都完全支持,而且类型检查还能帮你避免不少错误~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:18:36