javascript オブジェクトからnullの値を除去する

javascript オブジェクトからnullの値を除去する

javascriptで、オブジェクトからnullの値を除去するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

オブジェクトからnullの値を除去

オブジェクトからnullの値を除去するには、各keyの値を取得して「null」であれば「delete」で除去します。

const obj = {one: null, two: 2, three: null, four: 4};

Object.keys(obj).forEach(key => {
  if (obj[key] === null) delete obj[key];
});

console.log(obj); // {two: 2, four: 4}

ループは「 for – in 」や「 for – of 」も使用できます。

const obj1 = {one: null, two: 2, three: null, four: 4};

for (const key of Object.keys(obj1)) {
  if (obj1[key] === null) delete obj1[key];
}

console.log(obj1); // {two: 2, four: 4}

const obj2 = {one: null, two: 2, three: null, four: 4};

for (const key of Object.keys(obj2)) {
  if (obj2[key] === null) delete obj2[key];
}

console.log(obj2); // {two: 2, four: 4}

サンプルコード

以下は、
「取得」ボタンをクリックすると「null」が含まれているオブジェクトから「null」を除去して表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。関数はアロー関数で記述してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-75 mx-auto" style="margin-top:200px">

    <h2><span class="badge badge-warning"></span></h2>
    <h2><span class="badge badge-warning">結果</span></h2>

    <button type="button" onclick="hoge()" class="btn btn-raised btn-warning">
      取得
    </button>

  </div>

  <script>

    let obj = { one: null, two: null, three: 3 };

    // 表示用要素取得
    let elm = document.getElementsByClassName("badge")[0];

    // JSON 文字列に変換して表示
    elm.textContent = JSON.stringify(obj);

    const hoge = () => {

      // 表示用要素取得
      let elm = document.getElementsByClassName("badge")[1];

      for (const key in obj) {
        if (obj[key] === null) delete obj[key];
      }

      // JSON 文字列に変換して表示
      elm.textContent = JSON.stringify(obj);

    }

  </script>
</body>

</html>

除去されていることが確認できます。