javascript , lodash の コレクション操作の便利メソッド

● lodashのインストール

yarn add lodash
yarn add --dev @types/lodash

または

npm install lodash
npm install --D @types/lodash

● javascript , lodash の コレクション操作の便利メソッド

次のようなコレクション系データがあったとします。

var stageItems = [
	{ id: 5, name: "山田" },
	{ id: 6, name: "斎藤" },
	{ id: 7, name: "朝倉" },
	{ id: 8, name: "神山" },
	{ id: 9, name: "山田" },
];

● 検索して1件のみ返す find

import find from 'lodash/find';

// id = 6 なアイテムを選択します
const item = find(stageItems, { id:6 });

● 検索して複数件返す filter

// name:'山田' なアイテムを全て返します
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: "山田" },
};

● オブジェクトの 指定したキー以外の要素を取得する omit

const obj1 = {
  id: "hoge",
  name: "ほげ",
  phone: "123-4567"
};

const newObj = _.omit(obj1, ["id", "phone"]); // {name: "ほげ"}

● 何番目の要素なのかを検索

// id = 6 が 何番目の要素なのかを検索 ( 0 が先頭 )
const added_i = this.stageItems.findIndex(({id}) => id === 6);
alert( added_i ); // 2番目の要素なので 1

● コレクションのソート

const sortedItems = sortBy(items, "name");

// 逆順にする場合は .reverse() を実行します
const sortedItems = sortBy(items, "name").reverse();

// =>
// [
//   { 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; });
    },

● 配列の先頭 または 末尾から n個 削除

drop : 先頭 n個 削除
dropRight : 末尾 n個 削除

const data2 = _.dropRight(data, 3)    // 先頭 3つを削除
const data2 = _.dropRight(data, 2)    // 末尾 2つを削除

● コレクションからあるメンバだけを取り出したコレクションを作成して返す ( pluck )

const originalAttachFilesIDs = _.map(originalAttachFiles, 'fileID')
    const simpleItems = _.map(stageItems , (data) => {
      return { name: data.name }
    })

pluckメソッドは version 4 から .map() に統合されたようです。

// in 3.10.1
_.pluck(objects, 'a'); // → [1, 2]
_.map(objects, 'a'); // → [1, 2]

// in 4.0.0
_.map(objects, 'a'); // → [1, 2]

● オブジェクトのディープコピー

・JavaScriptではオブジェクトのコピーは参照コピーとなります。
・JavaScriptでは スプレッド構文やObject.assignを使ったコピーは1階層目は値がコピーされますが、
2階層以降にオブジェクトがあった場合 参照コピー となります。

オブジェクトをディープコピーしたい場合はこちらの cloneDeep()メソッドを使用します

const clonedItem = _.cloneDeep(item);

● javascript スプレッド構文とObject.assignを使ったコピーでは2階層目が参照コピーとなる例

const taguser1 = {
  id: 1,
  name: "hoge",
  tags:[
    {
      id:1,
      name: "Windows"
    } ,
    {
      id:2,
      name: "mac"
    }
  ]
};
const taguser2 = { ...taguser1 }; // 参照のコピー(オブジェクトをコピーした場合は参照がコピーされる)
const taguser3 = Object.assign({}, taguser1);

taguser1.id = 99999;
taguser1.tags[0].name = "ウィンドウズ"

console.log( '● taguser1' );
console.log( taguser1 );

console.log( '● taguser2' );
console.log( taguser2 );

console.log( '● taguser3' );
console.log( taguser3 );

結果

● taguser1 ​​​​​
{ id: 99999,
  name: 'hoge',
  tags: [ { id: 1, name: 'ウィンドウズ' }, { id: 2, name: 'mac' } ] }

● taguser2
{ id: 1,
  name: 'hoge',
  tags: [ { id: 1, name: 'ウィンドウズ' }, { id: 2, name: 'mac' } ] }

● taguser3
{ id: 1,
  name: 'hoge',
  tags: [ { id: 1, name: 'ウィンドウズ' }, { id: 2, name: 'mac' } ] }

参考 : https://qiita.com/waterada/items/62b32930d3c3668ff3d2

● lodash のバンドルサイズを小さくする

https://www.labnol.org/code/import-lodash-211117

import capitalize from 'lodash.capitalize';

const capitalizeFirstName = (name) => {
  const result = capitalize(name);
  console.log(response);
};

● memoize を 複数のキーで使用する

import memoize from 'lodoash/memoize';

const expensiveFunction = (input) => {
  return input * input;
};

const memoizedFunction = memoize(expensiveFunction);

console.log(memoizedFunction(5)); // Calculates the square of 5
console.log(memoizedFunction(5)); // Returns the cached value

 ↓

const multiply = (a, b) => {
  return a * b;
};

const resolver = (...args) => {
  return JSON.stringify(args);
};

const memoizedMultiply = _.memoize(multiply, resolver);

console.log(memoizedMultiply(1, 2)); // Calculates the product of 1 and 2 and caches the result
console.log(memoizedMultiply(1, 3)); // Calculates the product of 1 and 3 and caches the result
console.log(memoizedMultiply(1, 2)); // Returns the cached value
No.1961
06/07 16:02

edit