javascript オブジェクトの配列から指定したプロパティの値を抽出する
- 作成日 2022.03.18
- 更新日 2022.10.21
- javascript
- javascript
javascriptで、オブジェクトの配列から指定したプロパティの値を抽出するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 106.0.5249.103
指定したプロパティの値を抽出
指定したプロパティの値を抽出するには、「forEach」で条件を指定して抽出します。
実際に、「name」が「jiro」となっていることを条件を指定して抽出してみます。
※コールバック関数はアロー関数で記述してます。
const arr = [
{id: 1, name: "itiro"},
{id: 2, name: "jiro"},
{id: 3, name: "saburo"},
];
arr.forEach(o =>{
if(o.name === "jiro") console.log(o); // {id: 2, name: 'jiro'}
})
条件から新しいオブジェクトの配列を作成する場合は「filter」を使用します。
const arr = [
{id: 1, name: "itiro"},
{id: 2, name: "jiro"},
{id: 3, name: "saburo"},
{id: 4, name: "jiro"},
{id: 5, name: "jiro"},
];
const filterArr = arr.filter(o =>{
return o.name === "jiro"
})
// 元の配列
console.log(arr);
// 抽出した配列
console.log(filterArr);
実行結果
サンプルコード
以下は、
「実行」ボタンをクリックした際に、用意したオブジェクトの配列から指定したプロパティ値を取得して表示するだけのサンプルコードとなります。
※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: "saburo" },
];
window.onload = () => {
btn.onclick = () => {
//innerHTMLを使用して表示
arr.forEach(o => {
if (o.id === 3) foo.innerHTML = JSON.stringify(o) // {id: 2, name: 'jiro'}
})
}
}
</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-green-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-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>
実行結果を確認すると、指定したプロパティのみが表示されていることが確認できます。
-
前の記事
C# mysqlでトランザクションを使用する 2022.03.18
-
次の記事
node.js redisのキーを設定して取得する 2022.03.18
コメントを書く