javascript オブジェクトの配列から指定したプロパティの値を変更する

javascript オブジェクトの配列から指定したプロパティの値を変更する

javascriptで、オブジェクトの配列から指定したプロパティの値を変更するサンプルコードを掲載してます。「map」を使用して条件を指定することで可能です。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 109.0.5414.75

指定したプロパティの値を変更

指定したプロパティの値を変更するには、「map」に条件を指定して抽出します。

実際に、オブジェクトの配列を用意して条件を指定して変更してみます。

const arr = [
  {id: 1, name: "itiro"},
  {id: 2, name: "jiro"},
  {id: 3, name: "saburo"},
  {id: 4, name: "jiro"},
];

const result = arr.map(o =>{
  if(o.name === 'jiro') { 
    return { ...o, name: 'foo' } 
  } else{ 
    return o
  }
});

result.forEach(o =>{ console.log(o) })

実行結果

変更されていることが確認できます。

三項演算子を使用すると、もっと短く記述することが可能です。

const arr = [
  {id: 1, name: "itiro"},
  {id: 2, name: "jiro"},
  {id: 3, name: "saburo"},
  {id: 4, name: "jiro"},
];

const result = arr.map(o =>
  o.name === 'jiro' ? { ...o, name: 'foo' } : o
);

result.forEach(o =>{ console.log(o) })

サンプルコード

以下は、
「実行」ボタンをクリックした際に、用意したオブジェクトの配列から指定したプロパティ値を変更して表示するだけのサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  const arr = [
    { id: 1, name: "itiro" },
    { id: 2, name: "jiro" },
    { id: 3, name: "jiro" },
  ];

  window.onload = () => {

    result.innerHTML = JSON.stringify(arr)

    btn.onclick = () => {

      //innerHTMLを使用して表示    
      result.innerHTML = JSON.stringify(arr.map(o =>
          o.name === 'jiro' ? { ...o, name: 'foo' } : o
      ))

      txt.innerHTML = "実行結果"

    }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 id="txt" class="font-semibold text-green-500 text-lg mr-auto">元の値</h1>

      <p id="result" class="font-semibold text-lg mr-auto"></p>

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-green-500 text-green-700 font-semibold hover:text-white py-2 px-4 border border-green-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、指定したプロパティの値が変更されて表示されていることが確認できます。