【JavaScript】オブジェクトが特定のプロパティを持っているか確認する方法3選

hasOwnProperty()

存在すればtrue、しなければfalseを返します。継承されたプロパティは含めません。


const fruits = {
    name: 'Apple'
};

fruits.hasOwnProperty('name')  // true
fruits.hasOwnProperty('color') // false

in 演算子

存在すればtrue、しなければfalseを返します。継承されたプロパティも含めチェックします。


const fruits = {
    name: 'Apple'
};

'name' in fruits;    // true
'color' in fruits;   // false
'toString' in fruits // true

undefinedで比較

未定義のプロパティを参照しようとするとundefinedが返されるのでundefinedで比較することにより存在をチェックすることができます。


const fruits = {
    name: 'Apple'
};

undefined === fruits.name;  // false
undefined === fruits.color; // true

まとめ

定義したプロパティのみチェックしたい場合はhasOwnProperty()またはundefinedで比較、継承されたプロパティも含めてチェックしたい場合はin 演算子を使うと良いでしょう。

参考