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

ReactJS中移除对象数组重复值并生成唯一复选框的方案

解决对象数组去重后生成复选框的问题

嘿,这个问题我之前也碰到过!核心就是先把数组里重复的type值去掉,再用去重后的结果来生成复选框就行,给你两种常用的方案:

方案1:用Set快速提取唯一type值

这是最简洁的方式,利用Set自动去重的特性,先把所有type提取出来,再转成数组:

// 先对reportData按type去重
const uniqueTypes = [...new Set(reportData.map(item => item.type))];

然后在React里遍历这个去重后的数组生成复选框,记得给每个列表项加唯一的key(React要求列表元素必须有唯一标识):

{
  uniqueTypes.map((type) => (
    <FormControlLabel
      key={type} // 因为type已经去重了,用它当key很安全
      value={type}
      control={<Checkbox color="primary" />}
      label={type}
      labelPlacement="end"
    />
  ))
}

方案2:用reduce保留完整对象(如果后续需要用到其他字段)

如果你之后可能需要用到对象里的status或者其他字段,可以用reduce来保留完整的唯一对象:

const uniqueReportItems = reportData.reduce((acc, currentItem) => {
  // 检查累加器里有没有相同type的对象
  const hasSameType = acc.some(item => item.type === currentItem.type);
  if (!hasSameType) {
    acc.push(currentItem);
  }
  return acc;
}, []);

然后遍历这个数组的时候,直接取item.type当label就行:

{
  uniqueReportItems.map((item) => (
    <FormControlLabel
      key={item.type}
      value={item.type}
      control={<Checkbox color="primary" />}
      label={item.type}
      labelPlacement="end"
    />
  ))
}

两种方案都能解决你的问题,第一种更简洁,适合只需要type值的场景;第二种保留了完整对象,扩展性更强~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:52:34