findKey source npm

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

这个方法类似 _.find。 除了它返回最先被 predicate 判断为真值的元素 key,而不是元素本身。

参数

  1. object (Object)

    需要检索的对象

  2. [predicate=_.identity] (Function|Object|string)

    这个函数会处理每一个元素

返回值 (string|undefined)

返回匹配的 key,否则返回 undefined

示例

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (无法保证遍历的顺序)

// 使用了 `_.matches` 的回调结果
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'

// 使用了 `_.matchesProperty` 的回调结果
_.findKey(users, ['active', false]);
// => 'fred'

// 使用了 `_.property` 的回调结果
_.findKey(users, 'active');
// => 'barney'