2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScript の Map で異なるオブジェクトを同じキーにする方法は無い

Last updated at Posted at 2018-01-11

いまのところはできないらしい。

class C {
  constructor(v) {
    this.v = v
  }
}

let v1 = new C(1)
let v2 = new C(1)
const map = new Map()
map.set(v1, "ok")
console.log(map)             // Map { C { v: 1 } => 'ok' }
console.log(map.get(v2))     // => undefined

しかたがないので toKey() とか勝手に定義してあちこちで set / get の際に呼べばそりゃ動いたけど嫌。

class C {
  toKey() {
    return this.v.toString()
  }
}

map.set(v1.toKey(), "ok")
map.get(v2.toKey())     // => ok

素の連想配列なら簡潔にアクセスできるうえに toString() の結果をキーにしてくれたりして、新しくできた Map より使いやすいというのはどういうことだろうと思ったりした。

class C {
  constructor(v) {
    this.v = v
  }
  toString() {
    return this.v.toString()
  }
}

let c1 = new C(1)
let c2 = new C(1)
const map = {}
map[c1] = "ok"
console.log(map)         // { '1': 'ok' }
console.log(map[c2])     // => ok

参照

How to customize object equality for JavaScript Set - Stack Overflow
https://stackoverflow.com/questions/29759480/how-to-customize-object-equality-for-javascript-set

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?