0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

特定のvalueが入っているkeyをオブジェクト内から取り出したいときはlodashのfindKeyを使おう

Last updated at Posted at 2021-08-04

公式

サンプル

const obj = {
  hoge: 'fuga',
  foo: 'bar',
  hogehoge: 'fuga'
}

// キーを会得する
const key = _.findKey(obj,function(value, key) {
  return value === 'fuga'
});
// => findKeyには'hoge'が渡される

// おまけ: valueを会得する
obj[key]
// => 'fuga'

動作説明

_.findKey(object, [predicate=_.identity])

引数

  • object (Object): 検索したいオブジェクト
  • [predicate=_.identity] (Function): 検索するための関数を渡す、findKeyはこの関数を用いてオブジェクト内を検索する

returnされる値

  • 最初に一致した要素のキー

経緯

オブジェクト内で特定の値が入っているkeyを会得したいなと思い色々調べていた時に発見。最初はなんとなくこういう機能はJSに入っているだろうと思っていたけどまさか入っていないとは、、、結構ニッチな需要なのかな?

findKeyの内部コード

なるほどねー、Object.keysでkeyを配列にしたあとArray.prototype.someでvalueを会得、predicateで渡した関数を回して最初に合格した値を返すという訳ですね。蓋を開けるとシンプルだけど面白いなー。でもfindKey内でpredicateに第三引数としてobject渡しているのはなんでだろう?

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?