Home > Back-end >  i have an array of objects i wanna check if an elements exist in this array javascript
i have an array of objects i wanna check if an elements exist in this array javascript

Time:01-23

i have this array of objects

data= [
     { name: "name1",
       email: "[email protected]"},
     { name: "name2",
       email: "[email protected]"},
     { name: "name3",
       email: "[email protected]"},
]

i have the email on one of the users

"[email protected]"

i want to redirect the user in the users page if his email exist in the data array else redirect him to register page

CodePudding user response:

const data= [
     { name: "name1",
       email: "[email protected]"},
     { name: "name2",
       email: "[email protected]"},
     { name: "name3",
       email: "[email protected]"},
]

const email = "[email protected]"

console.log(data.some(item => item.email === email))

returns true if found. replace some with find to get the first element that matches

CodePudding user response:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const data = [{
    name: "name1",
    email: "[email protected]"
  },
  {
    name: "name2",
    email: "[email protected]"
  },
  {
    name: "name3",
    email: "[email protected]"
  },
]

const email = "[email protected]"

console.log(data.find(item => item.email === email))

  • Related