javascript lodashを使ってオブジェクトの配列から関数を使用して指定したキーの値を除去する
- 作成日 2021.08.16
- 更新日 2022.04.30
- javascript lodash
- javascript, lodash
javascriptで、lodashを使ってオブジェクトの配列から関数を使用して指定したキーの値を除去するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- lodash 4.17.21
- ブラウザ chrome 91.0.4472.77
lodash使用
こちらのサイトから最新版を確認して、CDN版を使用してます。
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
オブジェクトの配列から関数を使用して指定したキーの値を除去
オブジェクトの配列から関数を使用して指定したキーの値を除去には、「_.pullAllWith」を使用します。
'use strict';
let arr = [
{ 'name': 'm', 'age': 20 },
{ 'name': 'e', 'age': 25 },
{ 'name': 'b', 'age': 25 },
{ 'name': 'e', 'age': 27 },
{ 'name': 'e', 'age': 30 }
]
console.log(
_.pullAllWith(arr,[{'name': 'e','age': 25 }],_.isEqual)
);
// arrの値は変化する
console.log(
arr
);
arr = [
{ 'name': 'm', 'age': 20 },
{ 'name': 'e', 'age': 25 },
{ 'name': 'b', 'age': 25 },
{ 'name': 'e', 'age': 27 },
{ 'name': 'e', 'age': 30 }
]
console.log(
_.pullAllWith(arr,[{'age': 25 }],function(x,y){return x.age === y.age})
);
実行結果を確認すると、除去されていることが確認できます。
サンプルコード
以下は、
「実行」ボタンをクリックして、オブジェクトの配列から指定した関数を使用して対象のキーの値を除去して表示するだけのサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<script>
const hoge = () => {
const arr = [
{ 'name': 'm', 'age': 20 },
{ 'name': 'e', 'age': 25 },
{ 'name': 'b', 'age': 25 },
{ 'name': 'e', 'age': 27 },
{ 'name': 'e', 'age': 30 }
]
disp(arr, "foo");
disp(_.pullAllWith(arr,[{'name': 'e' }],(x,y)=>{return x.name === y.name}), "fuga");
}
//フロントに表示する関数
const disp = (arr, id) => {
let text = [];
arr.forEach((x, i) => text.push('<li class="list-group-item">' + JSON.stringify(arr[i]) + '</li>'))
document.getElementById(id).innerHTML = text.join('');
}
window.onload = () => {
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-400 text-lg mr-auto">配列</h1>
<ul id="foo" class="font-semibold text-lg mr-auto"></ul>
<h1 class="font-semibold text-red-400 text-lg mr-auto">実行後</h1>
<ul id="fuga" class="font-semibold text-lg mr-auto"></ul>
<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>
実行結果を確認すると、データが取り除かれてフロントに表示されていることが確認できます。
-
前の記事
jquery 指定した要素の後ろにhtmlタグを挿入する 2021.08.15
-
次の記事
C# comboBoxに配列の値を追加する 2021.08.16
コメントを書く