How to check if array of object contains a string

14,198

Since you need to check the object property value in the array, you can try with Array​.prototype​.some():

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

let arr = [
   {
    name: 'Jack',
    id: 1
   },
   {
    name: 'Gabriel',
    id: 2
   },
   {
    name: 'John',
    id: 3
   }
]
var r = arr.some(i => i.name.includes('Jack'));
console.log(r);
Share:
14,198

Related videos on Youtube

Gabriel Nessi
Author by

Gabriel Nessi

Updated on June 04, 2022

Comments

  • Gabriel Nessi
    Gabriel Nessi almost 2 years

    let's say I have an array of objects:

    let arr = [
       {
        name: 'Jack',
        id: 1
       },
       {
        name: 'Gabriel',
        id: 2
       },
       {
        name: 'John',
        id: 3
       }
    ]
    

    I need to check whether that array includes the name 'Jack' for example using:

    if (arr.includes('Jack')) {
       // don't add name to arr
    
    } else {
      // push name into the arr
    
    }
    

    but arr.includes('Jack') returns false, how can I check if an array of objects includes the name?

  • Gabriel Nessi
    Gabriel Nessi almost 5 years
    that worked! thanks
  • Mamun
    Mamun almost 5 years
    @GabrielNessi, you are most welcome:)