How to customize object equality for JavaScript Set

后端 未结 9 1365
臣服心动
臣服心动 2020-11-22 16:48

New ES 6 (Harmony) introduces new Set object. Identity algorithm used by Set is similar to === operator and so not much suitable for comparing objects:

9条回答
  •  不知归路
    2020-11-22 17:10

    To someone who found this question on Google (as me) wanting to get a value of a Map using an object as Key:

    Warning: this answer will not work with all objects

    var map = new Map();
    
    map.set(JSON.stringify({"A":2} /*string of object as key*/), "Worked");
    
    console.log(map.get(JSON.stringify({"A":2}))||"Not worked");
    

    Output:

    Worked

提交回复
热议问题