我有一个数组

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

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


当前回答

为了比较一个对象和另一个对象,我结合了for in循环(用于遍历对象)和some()。 你不必担心数组越界等问题,这样可以节省一些代码。一些文档可以在这里找到

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var  objectsFound = [];

for(let objectNumber in productList){
    var currentId = productList[objectNumber].id;   
    if (theDatabaseList.some(obj => obj.id === currentId)) {
        // Do what you need to do with the matching value here
        objectsFound.push(currentId);
    }
}
console.log(objectsFound);

我比较一个对象和另一个对象的另一种方法是使用object .keys()的嵌套for循环。长度来获取数组中对象的数量。下面的代码:

var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
var objectsFound = [];

for(var i = 0; i < Object.keys(productList).length; i++){
        for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
        if(productList[i].id === theDatabaseList[j].id){
            objectsFound.push(productList[i].id);
        }       
    }
}
console.log(objectsFound);

为了回答你的确切问题,如果你只是在一个对象中搜索一个值,你可以使用一个for in循环。

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

for(var ojectNumbers in vendors){
    if(vendors[ojectNumbers].Name === 'Magenic'){
        console.log('object contains Magenic');
    }
}

其他回答

你必须循环,这是没有办法的。

function seekVendor(vendors, name) {
  for (var i=0, l=vendors.length; i<l; i++) {
    if (typeof vendors[i] == "object" && vendors[i].Name === name) {
      return vendors[i];
    }
  }
}

当然,你可以使用像linq.js这样的库来让它更令人满意:

Enumerable.From(vendors).Where("$.Name == 'Magenic'").First();

(参见jsFiddle的演示)

我怀疑linq.js会比直接的循环更快,但当事情变得有点复杂时,它肯定会更灵活。

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

我解决这个问题的方法是使用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

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

const a = [{one:2},{two:2},{two:4}]
const b = a.filter(val => "two" in val).length;
if (b) {
   ...
}