我有一个数组

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

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


当前回答

我是这么做的

const found = vendors.some(item => item.Name === 'Magenic');

array.some()方法检查数组中是否至少有一个值符合条件,并返回一个布尔值。 从这里开始,你可以选择:

if (found) {
// do something
} else {
// do something else
}

其他回答

我解决这个问题的方法是使用ES6并创建一个函数来为我们检查。这个函数的好处是,它可以在整个项目中重复使用,以检查给定键和值的任何对象数组。

说得够多了,让我们看看代码

数组

const ceos = [
  {
    name: "Jeff Bezos",
    company: "Amazon"
  }, 
  {
    name: "Mark Zuckerberg",
    company: "Facebook"
  }, 
  {
    name: "Tim Cook",
    company: "Apple"
  }
];

函数

const arrayIncludesInObj = (arr, key, valueToCheck) => {
  return arr.some(value => value[key] === valueToCheck);
}

电话/使用

const found = arrayIncludesInObj(ceos, "name", "Tim Cook"); // true

const found = arrayIncludesInObj(ceos, "name", "Tim Bezos"); // false

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

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

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

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

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

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

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

我宁愿用正则表达式。

如果您的代码如下所示,

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

我推荐

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

Var without2 = (arr, args) => arr。过滤(v => v.id !== args.id); 例子:

without2 ([{id: 1}, {id: 1}, {id: 2}), {id: 2})

结果: without2 ([{id: 1}, {id: 1}, {id: 2}), {id: 2})