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

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

    Many answers here are good and pretty easy. But if your array of object is having a fixed set of value then you can use below trick:

    Map all the name in a object.

    vendors = [
        {
          Name: 'Magenic',
          ID: 'ABC'
         },
        {
          Name: 'Microsoft',
          ID: 'DEF'
        }
    ];
    
    var dirtyObj = {}
    for(var count=0;count

    Now this dirtyObj you can use again and again without any loop.

    if(dirtyObj[vendor.Name]){
      console.log("Hey! I am available.");
    }
    

提交回复
热议问题