How to determine if Javascript array contains an object with an attribute that equals a given value?

后端 未结 25 1800
借酒劲吻你
借酒劲吻你 2020-11-22 08:17

I have an array like

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


        
25条回答
  •  梦谈多话
    2020-11-22 09:03

    Testing for array elements:

    JS Offers array functions which allow you to achieve this relatively easily. They are the following:

    1. Array.prototype.filter: Takes a callback function which is a test, the array is then iterated over with is callback and filtered according to this callback. A new filtered array is returned.
    2. Array.prototype.some: Takes a callback function which is a test, the array is then iterated over with is callback and if any element passes the test, the boolean true is returned. Otherwise false is returned

    The specifics are best explained via an example:

    Example:

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

    Browser support:

    These 2 function are ES6 function, not all browsers might support them. To overcome this you can use a polyfill. Here is the polyfill for Array.prototype.some (from 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;
      };
    }

提交回复
热议问题