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

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

提交回复
热议问题