繁体   English   中英

Javascript | 集合中的唯一对象

[英]Javascript | Unique object in Set

如何防止Set对象填充重复的对象?

  [    
    {
        prop1: [{value: "val", disabled: true}] (1)
        prop2: [{value: [4, 5], disabled: true}] (1)
        prop3: [{value: "someOtherValue", disabled: true}] (1)
    },

    {
        prop1: [{value: "val", disabled: true}] (1)
        prop2: [{value: [4, 5], disabled: true}] (1)
        prop3: [{value: "someOtherValue", disabled: true}] (1)
    },
    {
        prop1: [{value: "otherValue", disabled: true}] (1)
        prop2: [{value: [3], disabled: true}] (1)
        prop3: [{value: "", disabled: true}] (1)
    },
  ]

因此,在遍历数组时,我检查Set对象是否包含重复项,但是即使重复,检查也始终返回false。

let s = new Set();

//for loop starts here

let check = s.has(obj) // false

if(check == false){
    s.add(obj);
}

对象是通过引用传递的,这意味着当您将它们添加到集合中时,即使它们完全相同,如果使用===检查,它们也将是不同的。

var a = {val1: 'hello', val2: 'there'}
var b = {val1: 'hello', val2: 'there'}
console.log(a === b) // false
console.log(a == b)  // false

要解决此问题,您可以编写以下内容,摘自本文

 var a = {val1: 'hello', val2: 'there'}; var b = {val1: 'hello', val2: 'there'}; function isEquivalent(a, b) { // Create arrays of property names var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); // If number of properties is different, // objects are not equivalent if (aProps.length != bProps.length) { return false; } for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; // If values of same property are not equal, // objects are not equivalent if (a[propName] !== b[propName]) { return false; } } // If we made it this far, objects // are considered equivalent return true; } console.log(a === b); // false console.log(a == b); // false console.log(isEquivalent(a, b)); // true 

使用此算法将检查对象而不是引用的实际值。

console.log(isEquivalent(a, b)) // true

也许比Ben的回答更短-公认更懒惰/不那么推荐-可以使用JSON进行比较:

let s = new Set()

arr.forEach(obj => (
    !s.has(JSON.stringify(obj)) && s.add(JSON.stringify(obj))
))

s = new Set([...s].map(o => JSON.parse(o)))

值得一提的是, 这仅在键值对的顺序相同时才有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM