Lodash,找到所有匹配元素的索引 [英] Lodash, find indexes of all matching elements

查看:118
本文介绍了Lodash,找到所有匹配元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用lodash,如何获取所有匹配元素的索引数组?例如:

Using lodash, how to get the array of indexes of all matching elements? As example:

Animals = [{Name: 'Dog', Id: 0},
          {Name: 'Cat', Id: 1},
          {Name: 'Mouse', Id: 2},
          {Name: 'Horse', Id: 3},
          {Name: 'Pig', Id: 3}]

然后我想用 Id == 3 查找所有元素的索引.

And then I want to find indexes of all elements with Id == 3.

预期输出:

Indexes = [3,4];

推荐答案

这是一个简短的解决方案:

Here is a short solution:

Indexes = _.keys(_.pickBy(Animals, {Id: 3}))

输出:

Indexes = ["3", "4"]


使用 pickBy 来选择元素,并使用 keys 来获取索引.


Use pickBy to pick element, and keys to get indexes.

pickBy 用于对象

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

创建一个由对象属性谓词组成的对象,该对象的谓词返回true.谓词由两个参数调用:(值,键).

Creates an object composed of the object properties predicate returns truthy for. The predicate is invoked with two arguments: (value, key).

https://lodash.com/docs/4.17.10#pickBy

但是在数组上使用时,它会返回一个类似

But when use on array, it return a object like

{
  3: {Name: "Horse", Id: 3},
  4: {Name: "Pig", Id: 3}
}

在此对象上使用 _.keys 来获取字符串数组中的所有键

use _.keys on this object to get all keys in string array

["3", "4"]

如果要获取数字数组,请使用 _.map

If you want to get number array, use _.map

_.map(_.keys(_.pickBy(Animals, {Id:3})), Number)

您将获得

[3, 4]

这篇关于Lodash,找到所有匹配元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆