我有一个数组

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

其他回答

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})

接受的答案仍然有效,但现在我们有一个ECMAScript 6本机方法[数组。find][1]和[数组。有些][2]来达到同样的效果。

Array.some

如果你只想确定一个元素是否存在,也就是说,你需要一个真/假的判断。

引用中数:

some()方法测试数组中是否至少有一个元素通过了所提供函数实现的测试。如果在数组中,它找到了提供的函数返回true的元素,则返回true;否则返回false。它不会修改数组。

Array.find

如果你想从数组else中获得匹配的对象,则使用find返回undefined。

引用中数:

find()方法返回所提供数组中满足所提供测试函数的第一个元素的值。如果没有满足测试函数的值,则返回undefined。

var arr = [
  {
    id: 21,
    label: 'Banana',
  },
  {
    id: 22,
    label: 'Apple',
  }
]

/* note : data is the actual object that matched search criteria 
  or undefined if nothing matched */

var data = arr.find(function(ele) {
    return ele.id === 21;
});

if (data) {
    console.log('found');
    console.log(data); // This is entire object i.e. `item` not boolean
}


/* note : doesExist is a boolean thats true or false depending on of whether the data was found or not */
var doesExist = arr.some(function(ele) {
    return ele.id === 21;
});


有一个由mozilla提供的IE的polyfill

目前最简单的方法:

if (vendors.findIndex(item => item.Name == "Magenic") == -1) {
  //not found item
} else {
  //found item 
}

我是这么做的

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

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

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

除非你想这样重组:

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

你可以这样做如果(vendor . magnetic)

你必须循环