yarn add lodash
yarn add --dev @types/lodash
次のようなコレクション系データがあったとします。
var stageItems = [
{ id: 5, name: "山田" },
{ id: 6, name: "斎藤" },
{ id: 7, name: "朝倉" },
{ id: 8, name: "神山" },
{ id: 9, name: "山田" },
];
// id = 6 なアイテムを選択します
const item = _.find(stageItems, { id:6 });
// lastName:'Tanaka' なアイテムを選択します
const item = _.filter(stageItems, { name:'山田' });
なお、コレクションだけでなくこのようなオブジェクトのオブジェクトでも検索可能です
var stageItems = {
5: { id: 5, name: "山田" },
6: { id: 6, name: "斎藤" },
7: { id: 7, name: "朝倉" },
8: { id: 8, name: "神山" },
9: { id: 9, name: "山田" },
};
// id = 6 が 何番目の要素なのかを検索 ( 0 が先頭 )
const added_i = this.stageItems.findIndex(({id}) => id === 6);
alert( added_i ); // 2番目の要素なので 1
const sortedItems = sortBy(items, "name");
// =>
// [
// { name: 'coffee', amount: 500 },
// { name: 'juice', amount: 500 },
// { name: 'lunch-a', amount: 1000 },
// { name: 'lunch-b', amount: 1200 },
// { name: 'smile', amount: 0 },
// { name: 'suger' }
// ]
引用: https://hbsnow.dev/blog/js-sort/
itemDelete: function ( argId ) {
alert("このidを削除します" + argId);
this.stageItems = _.remove(this.stageItems, function (o) { return o.id !== argId; });
},
drop : 先頭 n個 削除
dropRight : 末尾 n個 削除
const data2 = _.dropRight(data, 3) // 先頭 3つを削除
const data2 = _.dropRight(data, 2) // 末尾 2つを削除
const simpleItems = _.map(stageItems , (data) => {
return { name: data.name }
})
JavaScriptではオブジェクトのコピーは参照コピーとなります。 オブジェクトをディープコピーしたい場合はこちらのメソッドを使用します
const clonedItem = _.cloneDeep(item);