如何使用_lodash检查数组中匹配字段的首次出现? [英] How can I check an array for the first occurence where a field matches using _lodash?

查看:66
本文介绍了如何使用_lodash检查数组中匹配字段的首次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在使用以下内容:

I'm currently using the following:

   for (var i = 0; i < x.length; i++)
      if (x[i].id === userId)
         return x[i].name;

这将返回用户名.

是否有使用Lo-Dash进行此操作的更有效方法?请注意,该ID是唯一的,因此,如果找到该ID,则无需进行更多检查.

Is there a more efficient way to do this using Lo-Dash? Note that the id is unique so if found there's no need to check more.

推荐答案

使用_lodash是否有更有效的方法?

Is there a more efficient way to do this using _lodash?

不.您不会比普通的本机for循环效率高得多.但是您可以使用lodash用更少的代码来完成它.

No. You can't get much more efficient than a plain old native for loop. But you can do it in less code with lodash.

您可以使用 _.where (请注意,它返回一个新数组,而不是一个对象) :

You can use _.where (note that it returns a new array, rather than an object):

return _.where(x, { id: userId})[0];

但是它会比您的代码效率低,因为它在找到第一个匹配项时不会停止检查.它的键入时间略短.您真的不需要关心简单循环的效率如何.

But it's going to be less efficient than your code since it won't stop checking when it finds the first occurrence. It's just slightly shorter to type. You really shouldn't need to care about how efficient a simple loop is.

这篇关于如何使用_lodash检查数组中匹配字段的首次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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