我有一个数组

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

我如何检查这个数组,看看“Magenic”是否存在?我不想循环,除非迫不得已。我可能要处理几千条记录。


当前回答

不需要重新发明轮子循环,至少不显式地(使用箭头函数,仅限现代浏览器):

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

或者,更好的是,使用some,因为它允许浏览器在找到匹配的元素时立即停止,所以它会更快:

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 */
}

其他回答

我宁愿用正则表达式。

如果您的代码如下所示,

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

我推荐

/"Name":"Magenic"/.test(JSON.stringify(vendors))

2021解决方案*

Lodash .some (docs)是一个干净的解决方案,如果你使用_matchesProperty (docs)速记:

_.some(VENDORS, ['Name', 'Magenic'])

解释

这将遍历供应商数组,寻找Name键值为字符串'Magenic'的元素对象。一旦找到这个元素,它就返回true并停止迭代。如果在遍历整个数组后仍未找到该元素,则返回false。

代码片段

const vendor =[{名称:'Magenic', ID: 'ABC'},{名称:'Microsoft', ID: 'DEF'}]; console.log(_。some(vendor, ['Name', 'Magenic']));/ /正确的 < script src = " https://cdn.jsdelivr.net/npm/lodash@4.17.20 lodash.min.js " > < /脚本>

*注意,这使用流行的lodash库来实现最简单/最短的解决方案。对于那些感兴趣的人,我提供这个作为现有香草JS解决方案的替代方案。

不需要重新发明轮子循环,至少不显式地(使用箭头函数,仅限现代浏览器):

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

或者,更好的是,使用some,因为它允许浏览器在找到匹配的元素时立即停止,所以它会更快:

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 */
}

数组元素测试:

JS提供了数组函数,允许你相对容易地实现这一点。它们是:

array .prototype.filter:接受一个回调函数,这个回调函数是一个测试,然后数组被迭代,并根据这个回调进行过滤。返回一个新的过滤数组。 array .prototype.some:接受一个回调函数,它是一个测试,然后使用is callback迭代数组,如果任何元素通过测试,则返回布尔值true。否则返回false

具体细节最好通过一个例子来解释:

例子:

vendors = [ { Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' } //and so on goes array... ]; // filter returns a new array, we instantly check if the length // is longer than zero of this newly created array if (vendors.filter(company => company.Name === 'Magenic').length ) { console.log('I contain Magenic'); } // some would be a better option then filter since it directly returns a boolean if (vendors.some(company => company.Name === 'Magenic')) { console.log('I also contain Magenic'); }

浏览器支持:

这两个函数都是ES6函数,不是所有浏览器都支持。为了克服这个问题,你可以使用填充剂。下面是Array.prototype.some(来自MDN)的填充:

if (!Array.prototype.some) { Array.prototype.some = function(fun, thisArg) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) { return true; } } return false; }; }

因为OP询问了密钥是否存在的问题。

使用ES6 reduce函数返回布尔值的更优雅的解决方案可以是

const magenicVendorExists =  vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);

注意:reduce的初始参数是false,如果数组有键,它将返回true。

希望它有助于更好和更清晰的代码实现