javascript オブジェクトに指定したプロパティが存在するか判定する

javascript オブジェクトに指定したプロパティが存在するか判定する

javascriptで、hasOwnPropertyを使用して、オブジェクトに指定したプロパティが存在するか判定するサンプルコードを記述してます。ES2022からは「hasOwn」も使用できるようになりました。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.99

hasOwnProperty使い方

「hasOwnProperty」を使用すると、オブジェクトに指定したプロパティが存在するかを判定することが可能です。

const human = {
  name:'tanaka', 
  age:30,
  tel:123456
};

console.log(
  human.hasOwnProperty('name') // true
);

console.log(
  human.hasOwnProperty('address') // false
);

「in」を使用

「in」を使用して判定することも可能です。

const human = {
  name:'tanaka', 
  age:30,
  tel:123456
};

console.log( 'name' in human ) // true
console.log( 'address' in human ) // false

パフォーマンスは、結果が「true」でも「false」でも「in」の方がいいです。

「hasOwnProperty」と「in」の違い

また、「hasOwnProperty」はプロトタイプチェーンまではチェックしませんが、「in」はチェックします。
※「toString」や「valueOf」は、オブジェクトのプロトタイプチェーン

const human = {
  name:'tanaka', 
  age:30,
  tel:123456
};

console.log(
  human.hasOwnProperty('name') // true
);

console.log(
  human.hasOwnProperty('toString') // false
);

console.log(
  human.hasOwnProperty('valueOf') // false
);


console.log( 'name' in human ) // true
console.log( 'toString' in human ) // true
console.log( 'valueOf' in human ) // true

「hasOwn」

ES2022からは「hasOwn」も使用できます。

const human = {
  name:'tanaka', 
  age:30,
  tel:123456
};

console.log(
  Object.hasOwn(human, "name") // true
);

console.log(
  Object.hasOwn(human, "toString") // false
);

console.log(
  Object.hasOwn(human, "valueOf") // false
);

「undefined」と比較

他にもは「undefined」と比較する方法がありそうですが、

const human = {
  name:'tanaka', 
  age:30,
  tel:123456
};

console.log( human.name !== undefined ) // true 
console.log( human.address !== undefined ) // false

その場合は値が「undefined」だった場合は「undefined」と判定されてしまいます。

const human = {
  name:'tanaka', 
  age:30,
  tel:undefined
};

console.log( human.tel !== undefined ) // false 

console.log( human.hasOwnProperty('tel')) // true
console.log( 'tel' in human ) // true

配列に使用

「hasOwnProperty」は、以下のように配列にも使用することが可能です。

const arr = ['aaa','bbb']

console.log(arr.hasOwnProperty(0)); // true
console.log(arr.hasOwnProperty(1)); // false
console.log(arr.hasOwnProperty(2)); // false

生成したクラス内のオブジェクトにも使用できます。

class Hoge{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

const hoge = new Hoge("mebee", 35);

console.log(hoge.hasOwnProperty("name")); // true
console.log(hoge.hasOwnProperty("address")); // false

サンプルコード

以下は、
「実行」ボタンをクリックすると、テキストフォームに入力された値が用意しているオブジェクトのプロパティに存在するかを判定する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>

<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  function hoge() {

    const human = {
      name: 'tanaka',
      age: 30,
      tel: 123456
    };

    // フォームの値を取得
    const val = frm.value;
    // 結果を表示
    result.innerHTML = human.hasOwnProperty(val);

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main container">

    <h2><span id="result" class="badge bg-info">結果</span></h2>

    <div class="mb-3">
      <input id="frm" type="text" class="form-control">
    </div>

    <div class="row">
      <button id="btn" type="button" class="btn btn-warning">
        実行
      </button>
    </div>

  </div>

</body>

</html>

判定されていることが確認できます。