React Native中如何过滤数组并输出指定格式的ID列表?
问题描述
给定如下数组:
const arr = [ {id: 1, country: 'Austria'}, {id: 2, country: 'Germany'}, {id: 3, country: 'Austria'}, ];
尝试使用以下代码进行过滤:
arry.map((item,idx) => ( item.country== "Austria"?( console.log(item.id) ) : null ))
当前输出结果:
1 3
期望得到的输出格式:
1,3
需求是获取所有country为Austria的id,并以逗号分隔的字符串形式输出。
解决方案
你当前使用map的方式并不合适:map的作用是转换数组元素,而非过滤;且直接通过console.log逐个输出id,无法拼接成目标格式。正确的实现步骤如下:
方法一:filter + map + join
先筛选符合条件的元素,再提取id,最后拼接成字符串:
const arr = [ {id: 1, country: 'Austria'}, {id: 2, country: 'Germany'}, {id: 3, country: 'Austria'}, ]; const targetIds = arr .filter(item => item.country === 'Austria') .map(item => item.id) .join(','); console.log(targetIds); // 输出:1,3
方法二:reduce(一步完成)
使用reduce同时完成筛选和收集id,再拼接:
const arr = [ {id: 1, country: 'Austria'}, {id: 2, country: 'Germany'}, {id: 3, country: 'Austria'}, ]; const targetIds = arr.reduce((acc, item) => { if (item.country === 'Austria') { acc.push(item.id); } return acc; }, []).join(','); console.log(targetIds); // 输出:1,3
内容的提问来源于stack exchange,提问作者Vikram Singh
相关产品推荐
相关产品推荐

