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

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

    No need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):

    if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
      /* vendors contains the element we're looking for */
    }
    

    or, better yet:

    if (vendors.some(e => e.Name === 'Magenic')) {
      /* vendors contains the element we're looking for */
    }
    

    EDIT: If you need compatibility with lousy browsers then your best bet is:

    if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
      /* vendors contains the element we're looking for */
    }
    

提交回复
热议问题