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

如何使用reduce将含canais、topicos属性的对象数组拆分为两个数组

实现方案

方案1:两次map遍历(写法最简单,可读性最高)

如果你的数组数据量不大,直接用两次map方法是最简洁的选择:

// 你的原始数组
const channel = [
  {canais: 'canal1', topicos: 'topico1'},
  {canais: 'canal2', topicos: 'topico2'},
  {canais: 'canal3', topicos: 'topico3'}
];

// 提取两个目标数组
const canais = channel.map(item => item.canais);
const topicos = channel.map(item => item.topicos);

运行后得到的canais和topicos就是你需要的字符串数组。

方案2:单次reduce遍历(性能更优)

如果数组数据量很大,不想重复遍历两次数组,可以用reduce一次遍历完成提取:

const [canais, topicos] = channel.reduce((result, currentItem) => {
  result[0].push(currentItem.canais);
  result[1].push(currentItem.topicos);
  return result;
}, [[], []]);

这种写法只需要遍历一次原数组,处理大量数据时性能更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:45:06