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

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

    May be too late, but javascript array has two methods some and every method that returns a boolean and can help you achieve this.

    I think some would be most appropriate for what you intend to achieve.

    vendors.some( vendor => vendor['Name'] !== 'Magenic' )
    

    Some validates that any of the objects in the array satisfies the given condition.

    vendors.every( vendor => vendor['Name'] !== 'Magenic' )
    

    Every validates that all the objects in the array satisfies the given condition.

提交回复
热议问题