Javascript search for an object key in a set

前端 未结 6 741
太阳男子
太阳男子 2021-01-14 09:46

Is it possible to use the javascript \"Set\" object to find an element with a certain key? Something like that:

let myObjects = [{\"name\":\"a\", \"value\":0         


        
6条回答
  •  星月不相逢
    2021-01-14 09:56

    If you want to do this with a Set, then the object you're searching for has to be the same object that was added, not an anonymous object.

    So, you could achieve what you're looking for if it was set up like this:

    let myObject = {"name": "a", "value": 0};
    let set = new Set([myObject]);
    
    console.log(set.has(myObject));
    

    This is because set.has() uses SameValueZero() under the hood.

    Here is the spec for set.has(): http://www.ecma-international.org/ecma-262/6.0/#sec-set.prototype.has

    And for SameValueZero(): http://www.ecma-international.org/ecma-262/6.0/#sec-samevaluezero

提交回复
热议问题