I am trying to implement a Set on the dropdown list object and within the Set, I am using map function . I have tried two different ways by using Set but there has been no removal of the duplicates. Here, devices is the object and from there am trying to execute Set with map function. devices is the object.

enter image description here

Here is the dropdown list which is showing repeated values. On the right hand-side , you can see the devices array being shown. The dropdown list should show 4-5 options of device_id. Please help. enter image description here

推荐答案

集合不会移除具有不同引用的对象.即使对象具有相同的值,这些对象也不会被视为相同的:

const arr = [
  // These objects look the same but are both unique objects in memory, so they have different references
  {foo: 1},
  {foo: 1}
];

const res = [...new Set(arr)];
console.log(res); // [{foo: 1}, {foo: 1}]

您的情况类似于上面的示例,因为JSX <option ...></option>在幕后创建对象.

相反,我建议您使用different method来对devices数组中的重复对象进行重复数据消除.仅当您的devices数组在useMemo()的帮助下更改时(假设devices为状态),您才能执行此重复数据消除,例如:

const uniqueDevices = useMemo(() => {
   const uniqueMap = new Map(devices.map(device => [
     device.device_id, // deduplicate by the `device_id` property
     device
   ]);
   return [...uniqueMap.values()];
}, [devices]);

// please post your code as text so we don't have to retype this :)
return <div>
  <h1>Devices</h1>
  <select>
    { devices ?
      ? uniqueDevices.map(device => <option key={device.device_id}>{device.device_id}</option>)
      : null
    }
  </select>
</div>

如果您只需要在JSX中引用每个device对象的device_id属性,那么您可以继续使用Set()来删除重复项,如@andrew所示:

const uniqueDeviceIds = useMemo(() => 
  Array.from(new Set(devices.map(device => device.device_id)))
, [devices]);

return <div>
  <h1>Devices</h1>
  <select>
    { devices ?
      ? uniqueDeviceIds.map(deviceId => <option key={deviceId}>{device_id}</option>)
      : null
    }
  </select>
</div>

Javascript相关问答推荐

在JavaScript中逐一播放随机生成的音频文件数组

访客柜台的风格React.js

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

类型自定义lazy Promise. all

在网页上添加谷歌亵渎词

为什么promise对js中的错误有一个奇怪的优先级?

WebGL 2.0无符号整数输入变量

保持物品顺序的可变大小物品分配到平衡组的算法

变量的值在Reaction组件中的Try-Catch语句之外丢失

如何使用JavaScript拆分带空格的单词

当输入字段无效时,我的应用程序不会返回错误

覆盖加载器页面避免对页面上的元素进行操作

如何在 Select 文本时停止Click事件?

匹配一个或多个可选重复的特定模式

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

Pevent触发material 用户界面数据网格中的自动保存

如何让SVG图标在被点击和访问后改变 colored颜色 ,并在被访问后取消点击时恢复到原来的 colored颜色 ?

在Java脚本中构建接口的对象

递增/递减按钮React.js/Redux