LoginSignup
0
0

More than 3 years have passed since last update.

lodash備忘録

Last updated at Posted at 2020-02-01

lodash知っとくと捗る

調べたら情報は出てくるけど少しでもその時間を少なくするために備忘録をつける。
新しいものを使うたびに増やしていくスタイルにしよう

・find

  • 文字通り検索系。配列を検索する。
  • 例)ユーザーIDをキーにusers配列を探しpayloadでもらったidに該当したオブジェクトを返却する
// payloadがhogeのとき
const user = _.find(this.users, {
      userId: payload.userId
    })
// => user: {userId: 'hoge', userName: 'fuga'}

・findIndex

  • findのindex版。こちらはキーに該当するオブジェクトが配列の何番目にあったかを返す。

this.TabIndex = _.findIndex(this.tabs, {
      sikCd: node.sikcd
    })
// => 1

cloneDeep

  • 文字通りディープコピーする。これは結構使う。
  • シャローコピーとディープコピーの違いはコチラで。
  • 初学者の頃、変更前・変更後の比較の処理でシャローコピーをしていて、値が共有されていてハマりまくっていたのでこれはすぐ覚えた。

let obj = {
 title: "HOGE",
 description: "FUGA"
}
const obj2 = cloneDeep(obj) // => obj2: {title: "HOGE", description: "FUGA"}

padStart

  • 桁を0埋めとかでそろえたいとき

_.padStart(5, 2, '0'); // => '05'
_.padStart(12, 4, '0'); // => '0012'
_.padStart(100, 2, '0'); // => '100'

times

  • for文を簡潔にしたもの
length = 100
  hoge = _.times(length, i => {
      // やりたい処理
  })
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0