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

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

    My approach to solving this problem is to use ES6 and creating a function that does the check for us. The benefit of this function is that it can be reusable through out your project to check any array of objects given the key and the value to check.

    ENOUGH TALK, LET'S SEE THE CODE

    Array

    const ceos = [
      {
        name: "Jeff Bezos",
        company: "Amazon"
      }, 
      {
        name: "Mark Zuckerberg",
        company: "Facebook"
      }, 
      {
        name: "Tim Cook",
        company: "Apple"
      }
    ];
    

    Function

    const arrayIncludesInObj = (arr, key, valueToCheck) => {
      let found = false;
    
      arr.some(value => {
        if (value[key] === valueToCheck) {
          found = true;
          return true; // this will break the loop once found
        }
      });
    
      return found;
    }
    

    Call/Usage

    const found = arrayIncludesInObj(ceos, "name", "Tim Cook"); // true
    
    const found = arrayIncludesInObj(ceos, "name", "Tim Bezos"); // false
    

提交回复
热议问题