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

后端 未结 25 1164
借酒劲吻你
借酒劲吻你 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 08:58

    To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here

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

    An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:

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

    To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.

    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');
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:02

    The accepted answer still works but now we have an ECMAScript 6 native method [Array.find][1] to achieve the same effect.

    Quoting MDN:

    The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

    var arr = []; 
    var item = {
      id: '21',
      step: 'step2',
      label: 'Banana',
      price: '19$'
    };
    
    arr.push(item);
    /* 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
    }
    

    See my jsfiddle link There is a polyfill for IE provided by mozilla

    0 讨论(0)
  • 2020-11-22 09:02

    As per ECMAScript 6 specification, you can use findIndex.

    const magenicIndex = vendors.findIndex(vendor => vendor.Name === 'Magenic');

    magenicIndex will hold either 0 (which is the index in the array) or -1 if it wasn't found.

    0 讨论(0)
  • 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;
      };
    }

    0 讨论(0)
  • 2020-11-22 09:03

    I would rather go with regex.

    If your code is as follows,

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

    I would recommend

    /"Name":"Magenic"/.test(JSON.stringify(vendors))
    
    0 讨论(0)
  • 2020-11-22 09:04
    const check = vendors.find((item)=>item.Name==='Magenic')
    
    console.log(check)
    

    Try this code.

    If the item or element is present then the output will show you that element. If it is not present then the output will be 'undefined'.

    0 讨论(0)
提交回复
热议问题