我有一个数组

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

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


当前回答

根据ECMAScript 6规范,您可以使用findIndex。

const magenicIndex =供应商。findIndex(供应商=>供应商。= = = ' Magenic')名称;

magenicIndex将保留0(这是数组中的索引)或-1(如果没有找到)。

其他回答

目前最简单的方法:

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

除非你想这样重组:

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

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

你必须循环

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

没有“神奇”的方法可以在没有循环的情况下检查数组中的内容。即使你使用某个函数,这个函数本身也会使用循环。您可以做的是,一旦找到要查找的内容,就立即跳出循环,以最小化计算时间。

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

你可以使用lodash。如果lodash库对你的应用程序来说太沉重,可以考虑将不需要的不使用的函数分块。

let newArray = filter(_this.props.ArrayOne, function(item) {
                    return find(_this.props.ArrayTwo, {"speciesId": item.speciesId});
                });

这只是一种方法。另一个可以是:

var newArray=  [];
     _.filter(ArrayOne, function(item) {
                        return AllSpecies.forEach(function(cItem){
                            if (cItem.speciesId == item.speciesId){
                            newArray.push(item);
                          }
                        }) 
                    });

console.log (arr);

上面的例子也可以在不使用任何库的情况下重写,比如:

var newArray=  [];
ArrayOne.filter(function(item) {
                return ArrayTwo.forEach(function(cItem){
                    if (cItem.speciesId == item.speciesId){
                    newArray.push(item);
                  }
                }) 
            });
console.log(arr);

希望我的回答能有所帮助。

接受的答案仍然有效,但现在我们有一个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