如何在React中去除API填充的下拉菜单重复值
下拉菜单重复值问题:需要显示唯一的制造商、省份、城市选项
背景
- API返回约50条产品数据
- 部分产品共享相同的制造商、省份或城市
目标
- 每个下拉菜单仅显示唯一值,优化筛选体验
当前问题
- 下拉菜单填充了重复选项,造成冗余
- 问题可视化:

现有代码
export const Dropdown: React.FC<DropdownProps> = ({ data, onChange, value, filterType, }) => { const filteredData = data[0].equipments; // Filter the data based on the filterType const filteredOptions = filteredData.filter((i) => { if (filterType === "manufacturer") { return i.manufacturer; } if (filterType === "state") { return i.state; } if (filterType === "city") { return i.city; } return false; }); return ( <> <Select placeholder={getCustomPlaceholder(filterType)} value={value} onChange={onChange} > {filteredOptions.map((i) => ( <option key={i.id} value={i[filterType]}> {i[filterType]} </option> ))} </Select> </> ); };
解决建议
核心是对选项进行去重处理,以下是两种实用方案:
方案1:用Set快速去重(极简实现)
利用Set的唯一性特性提取并去重目标字段:
export const Dropdown: React.FC<DropdownProps> = ({ data, onChange, value, filterType, }) => { const filteredData = data[0].equipments; // 提取目标字段、过滤空值、去重 const uniqueValues = Array.from( new Set(filteredData.map(item => item[filterType]).filter(Boolean)) ); return ( <> <Select placeholder={getCustomPlaceholder(filterType)} value={value} onChange={onChange} > {uniqueValues.map((val) => ( <option key={val} value={val}> {val} </option> ))} </Select> </> ); };
filter(Boolean)用于过滤API返回的空值(可选,根据实际数据情况调整)- 直接用唯一值作为key,避免重复渲染问题
方案2:用Reduce手动构建唯一集合(保留原对象)
如果需要保留原产品对象的其他属性,可使用Map存储已出现的值:
export const Dropdown: React.FC<DropdownProps> = ({ data, onChange, value, filterType, }) => { const filteredData = data[0].equipments; // 构建唯一值映射,确保每个值仅保留第一个出现的对象 const uniqueMap = filteredData.reduce((map, item) => { const val = item[filterType]; if (val && !map.has(val)) { map.set(val, item); } return map; }, new Map()); const uniqueOptions = Array.from(uniqueMap.values()); return ( <> <Select placeholder={getCustomPlaceholder(filterType)} value={value} onChange={onChange} > {uniqueOptions.map((item) => ( <option key={item[filterType]} value={item[filterType]}> {item[filterType]} </option> ))} </Select> </> ); };
- 此方案适合后续需要基于原对象扩展逻辑的场景
内容的提问来源于stack exchange,提问作者jrad09
相关产品推荐
相关产品推荐

