如何确定Javascript数组是否包含具有等于给定值的属性的对象? [英] How to determine if Javascript array contains an object with an attribute that equals a given value?

查看:97
本文介绍了如何确定Javascript数组是否包含具有等于给定值的属性的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的数组

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    } and so on... 
];

如何检查此数组以查看Magenic是否存在?我不想循环,除非我必须。我正在处理几千条记录。

How do I check this array to see if Magenic exists? I don't want to loop, unless I have to. I'm working with potentially a couple thousand records.

更新

自这是一篇很受欢迎的帖子,我想我会分享一些新发现的东西。似乎@CAFxX已经分享了这个!我应该经常阅读这些内容。我遇到了 https://benfrain.com/understanding-native-javascript-array-methods /

Since this has been a popular post, I thought I'd share something new I found. And it appears @CAFxX has already shared this! I should read these more often. I came across https://benfrain.com/understanding-native-javascript-array-methods/.

vendors.filter(function(vendor){ return vendor.Name === "Magenic" });

使用ECMAScript 2015,使用新的箭头功能更简单:

And with ECMAScript 2015 it is even simpler using the new arrow functions:

vendors.filter(vendor => (vendor.Name === "Magenic"));


推荐答案

2018编辑:这个答案是从2011年开始,之前浏览器广泛支持阵列过滤方法和箭头功能。请查看 CAFxX的答案

2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.

没有魔术在没有循环的情况下检查数组中某些东西的方法。即使你使用某个函数,函数本身也会使用循环。你可以做的就是在找到你想要的东西时尽快摆脱循环,以最大限度地减少计算时间。

There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.

var found = false;
for(var i = 0; i < vendors.length; i++) {
    if (vendors[i].Name == 'Magenic') {
        found = true;
        break;
    }
}

这篇关于如何确定Javascript数组是否包含具有等于给定值的属性的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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