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

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

    You have to loop, there is no way around it.

    function seekVendor(vendors, name) {
      for (var i=0, l=vendors.length; i

    Of course you could use a library like linq.js to make this more pleasing:

    Enumerable.From(vendors).Where("$.Name == 'Magenic'").First();
    

    (see jsFiddle for a demo)

    I doubt that linq.js will be faster than a straight-forward loop, but it certainly is more flexible when things get a little more complicated.

提交回复
热议问题