どうも、ちょげ(@chogetarou)です。
連想配列(Associative Array)の特定のキー(key)が存在するかどうか確認する方法を紹介します。
方法

連想配列のキー(key)の存在チェックをする方法は、ObjectとMapで異なります。
Object(オブジェクト)の場合
Object(オブジェクト)のキーの存在チェックをする方法は、3つあります。
hasOwnProperty()
ひとつめは、hasOwnPropertyを使う方法です。
まず、ObjectからhasOwnProperty()を呼び出します。
そして、hasOwnProperty()の引数に、存在を確認するキー(key)を指定します。
//objにkey(キー)が存在するか
obj.hasOwnProperty(key)
上記のhasOwnProperty()は、呼び出したObject(オブジェクト)に引数のキー(key)が存在すれば「true」、存在しなければ「false」を返します。
使用例
const nums = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
}
console.log(nums.hasOwnProperty("one"))
console.log(nums.hasOwnProperty("six"))
console.log(nums.hasOwnProperty("four"))
出力:
true
false
true
in
ふたつめは、「in」演算子を使う方法です。
具体的な方法としては、「in」演算子の左辺にキー(key)、右辺にObjectを指定します。
//objにkeyが存在するか
key in obj
上記の「in」演算子は、右辺のObjectに左辺のキーが存在すれば「true」、存在しなければ「false」を返します。
使用例
const nums = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
}
console.log("one" in nums)
console.log("ten" in nums)
console.log("four" in nums)
出力:
true
false
true
undefined
みっつめは、undefinedを使う方法です。
まず、Objectの存在チェックするキーにアクセスします。
そして、アクセスした結果が「undefined」かどうか「===」もしくは「!==」で調べます。
//objにkeyが存在するか
obj[key] === undefined //存在しない場合にtrue, 存在する場合にfalse
obj[key] !== undefined //存在する場合にtrue, 存在しない場合にfalse
Objectのキー(key)にアクセスした結果が「undefined」と等しいならば、キーは存在しません。
Objectのキー(key)にアクセスした結果が「undefined」でなければ、キーは存在します。
使用例
const nums = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
}
console.log(nums["one"] === undefined)
console.log(nums["seven"] === undefined)
console.log(nums["three"] === undefined)
出力:
false
true
false
Map(マップ)の場合
Map(マップ)のキーの存在チェックをするには、has()を使います。
まず、Mapからhas()を呼び出します。
そして、has()の引数に、キーを指定します。
//map=マップ、key=キー
map.has(key)
上記のhas()は、呼び出したMap(マップ)に引数のキーが存在すれば「true」、存在しなければ「false」を返します。
使用例
const nums = new Map();
nums.set("one", 1)
nums.set("two", 2)
nums.set("three", 3)
nums.set("four", 4)
nums.set("five", 5)
console.log(nums.has("two"))
console.log(nums.has("ten"))
console.log(nums.has("three"))
出力:
true
false
true
まとめ
連想配列のキー(key)の存在チェックをする方法は、ObjectとMapで異なります。
- Objectの場合
obj.hasOwnProperty(key)
key in obj
obj[key] === undefined
obj[key] !== undefined
- Mapの場合
map.has(key)
コメント