Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects return object when condition matched

I have an array which have value of id, email and password.

let array = [
 {id: hyu, email: [email protected], password: 123},
 {id: rft, email: [email protected], password: 456},
 {id: ght, email: [email protected], password: 789},
 {id: kui, email: [email protected], password: 679}
]

Now I would like to return that object when my condition is matched. For that I created a function using javascript some function but I want to return the object and we know that some function return boolean.

I don't have any idea how to do this.

My code is:

const isEmailExists = (email, array) => {
  return array.some(function(el) {
    return el.email === email;
  });
};

if (isEmailExists("[email protected]", array) == true) {
  // I want to work here with returned objects i.e on success case
} else {
  // error case
}

Any help is really appreciated

like image 267
Aks Avatar asked Apr 03 '19 09:04

Aks


2 Answers

You can make use of .filter() and check if the filtered array has a length of more than 0:

let array = [
 {id: 'hyu', email: '[email protected]', password: 123},
 {id: 'rft', email: '[email protected]', password: 456},
 {id: 'ght', email: '[email protected]', password: 789},
 {id: 'kui', email: '[email protected]', password: 679}
]

let filtered = array.filter(row => row.email === '[email protected]');

console.log(filtered);

if (filtered.length > 0) { /* mail exists */ }
else { /* mail does not exist */ }
like image 168
Sebastian Kaczmarek Avatar answered Nov 15 '22 23:11

Sebastian Kaczmarek


Assuming the email is unique, you can use find(). This will return null if not email does not exist.

let array = [{"id":"hyu","email":"[email protected]","password":123},{"id":"rft","email":"[email protected]","password":456},{"id":"ght","email":"[email protected]","password":789},{"id":"kui","email":"[email protected]","password":679}];

const getObject = (email, array) => {
  return array.find(function(el) {
    return el.email === email;
  }) || null;
};

console.log(getObject("[email protected]", array));

Shorter Version:

const getObject = (email, array) => array.find(el => el.email === email ) || null;
like image 23
Eddie Avatar answered Nov 15 '22 23:11

Eddie