LoginSignup
163
123

More than 3 years have passed since last update.

jsでのプロパティの存在チェック方法をまとめてみる

Last updated at Posted at 2019-02-19

なりゆき

レビューしてるなかでプロパティチェック方法を考えてたら何個かパターンがあるのでまとめてみた

ざっくばらん

Object.keys + Array.prototype.indexOf

let user = {
  id: 1,
  name: 'hoge'
};

console.log(Object.keys(user).indexOf('name') !== -1) // true
console.log(Object.keys(user).indexOf('mailaddress') !== -1) // false

一度キーの配列にしてから、配列内に対象のキー名があるかを見る方法
二回メソッド呼ぶ必要があって冗長・・・

Object.prototype.hasOwnProperty

let user = {
  id: 1,
  name: 'hoge'
};

console.log(user.hasOwnProperty('name')) // true
console.log(user.hasOwnProperty('mailaddress')) // false

オブジェクトの対象のプロパティの有無を返します
この時継承されていないプロパティしか見ないので注意

in演算子

let user = {
  id: 1,
  name: 'hoge'
};

console.log('name' in user) // true
console.log('mailaddress' in user) // false

最近知った()
Object.prototype.hasOwnPropertyとだいたい同様で、オブジェクトの対象のプロパティの有無を返します
こちらは継承元までさかのぼってプロパティを見ます

163
123
1

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
163
123