javascript オブジェクトの配列のプロパティを更新する
- 作成日 2022.11.11
- javascript
- javascript

javascriptで、オブジェクトの配列のプロパティを更新するサンプルコードを記述してます。配列の各要素を操作できる「map」とスプレッド構文を使用して更新します。最初の値のみを更新する場合は「for-of」などを使用します。
環境
- OS windows11 home
- Apache 2.4.43
- ブラウザ chrome 107.0.5304.88
更新方法
スプレッド構文を使用すると、以下のように、オブジェクトの複製や更新が可能なため、これと「map」を使用して更新します。
const obj1 = {name: 'aaa', age: 10};
const clonedObj = { ...obj1 };
console.log(clonedObj); // {name: 'aaa', age: 10}
const changedObj = { ...obj1, age: 30 };
console.log(changedObj); // {name: 'aaa', age: 30}
実際に「map」と「スプレッド構文」を使って更新してみます。
const arr = [
{name: 'aaa', age: 10},
{name: 'bbb', age: 20},
{name: 'aaa', age: 20},
];
const newArr = arr.map(obj => {
if (obj.name === "aaa") return {...obj, age: 30};
return obj;
});
console.log(newArr);
実行結果

初めにみつかった値のみを更新したい場合は「for…of」で「break」を使用します。
const arr = [
{name: 'aaa', age: 10},
{name: 'bbb', age: 20},
{name: 'aaa', age: 20},
];
for (const obj of arr) {
if (obj.name === "aaa") {
obj.age = 30;
break;
}
}
console.log(arr);
実行結果

サンプルコード
以下は、
「実行」ボタンをクリックして、用意したオブジェクトの配列を更新して結果を表示するサンプルコードとなります。
※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 = [
{ name: 'kusano', age: 20 },
{ name: 'sasaki', age: 25 },
{ name: 'sasaki', age: 25 },
{ name: 'tanaka', age: 30 },
{ name: 'takagi', age: 30 },
{ name: 'kusano', age: 20 },
{ name: 'kusano', age: 40 }
]
const hoge = () => {
result.innerHTML = JSON.stringify(arr.map(obj => {
if (obj.name === "sasaki") return { ...obj, age: 100 };
return obj;
}));
}
window.onload = () => {
foo.innerHTML = JSON.stringify(arr);
btn.onclick = () => { hoge() };
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-red-500 text-lg mr-auto">実行結果</h1>
<p id="result" class="font-semibold text-lg mr-auto"></p>
<h1 class="font-semibold text-neutral-500 text-lg mr-auto">用意したオブジェクトの配列</h1>
<p id="foo" class="font-semibold text-lg mr-auto"></p>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、更新した結果が表示されていることが確認できます。

-
前の記事
redmine バージョンを確認する 2022.11.11
-
次の記事
redmine LDAPでエラー「Internal error An error occurred on the page you were trying to access.」が発生した場合の対処法 2022.11.11
コメントを書く