如何使用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
相关产品推荐
相关产品推荐

