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

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

    As the OP has asked the question if the key exists or not.

    A more elegant solution that will return boolean using ES6 reduce function can be

    const magenicVendorExists =  vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);
    

    Note: The initial parameter of reduce is a false and if the array has the key it will return true.

    Hope it helps for better and cleaner code implementation

提交回复
热议问题