如何确定 Javascript 数组是否包含具有等于给定值的属性的对象?

新手上路,请多包涵

我有一个像

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

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

原文由 David Lozzi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 774
2 个回答

2018 年编辑:这个答案来自 2011 年,当时浏览器还没有广泛支持数组过滤方法和箭头函数。看看 CAFxX 的回答

没有“神奇”的方法可以在没有循环的情况下检查数组中的某些内容。即使您使用某些函数,该函数本身也会使用循环。您可以做的是在您找到所需内容后立即跳出循环,以最大限度地减少计算时间。

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

原文由 Alex Turpin 发布,翻译遵循 CC BY-SA 4.0 许可协议

无需重新发明车轮循环,至少不是明确的(使用 箭头函数仅限现代浏览器):

 if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
  /* vendors contains the element we're looking for */
}

或者, 更好 的是,使用 一些,因为它允许浏览器在找到一个匹配的元素后立即停止,因此它会更快:

 if (vendors.some(e => e.Name === 'Magenic')) {
  /* vendors contains the element we're looking for */
}

或等效的(在本例中) 查找

 if (vendors.find(e => e.Name === 'Magenic')) {
  /* same result as above, but a different function return type */
}

您甚至可以使用 findIndex 获取该元素的位置:

 const i = vendors.findIndex(e => e.Name === 'Magenic');
if (i > -1) {
  /* vendors contains the element we're looking for, at index "i" */
}

而且,如果您需要与糟糕的浏览器兼容,那么最好的选择是:

 if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
  /* vendors contains the element we're looking for */
}

原文由 CAFxX 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题