-1

I am trying to use an array map for checking if same username and password exist in an object array

database.map((obj)=>{
  if(values.name  === obj.name && values.password===obj.password){
    console.log("login success");
  } else {
    console.log("login Failed");
  }
});

3
  • 1
    So what's the question? Commented Nov 18, 2022 at 4:41
  • 1
    What do you mean? On what are you using an array map, and what do you want to know? Commented Nov 18, 2022 at 4:45
  • 1
    please specify what do you want to do, what you have tried, expected and actual result. Commented Nov 18, 2022 at 4:45

3 Answers 3

0

You may use find for conditions:

const result = database.find((val)=> {
return val.name === obj.name && val.password === obj.password;
})

if(result){
console.log("login success");
}
else{
console.log("login failed");
}
Sign up to request clarification or add additional context in comments.

3 Comments

You mean find(), right? filter will always return an array, so result will always be truthy.
I was about to write that. That's why I checked the truthy value of length.
@danh You are right!
0

I'm not really sure if this is the answer you are looking for, but if you want to check data you should use filter instead of map. Map is to create a new array (with the same amount of elements).

const matches = database.filter(o => o.name === values.name && o.password === values.password);

That will return a new array if the condition is met. You can check is there is any.

if (matches.length) {
  console.log("login success");
} else {
  console.log("login Failed");
}

2 Comments

This is the right way to use filter(), but find() is a better choice here (also), since the check is only for the existence of an object matching the condition. With find(), once one is found, you stop looking.
Thanks. I forgot about that one. Handy.
0
let database = [{ name: 'Krishna', password: 'Krishna@123' }, { name: 'Radhe', password: 'Radhe@123' }];
let values = { name: 'Radhe', password: 'Radhe@123' };
let status=database.some(obj=>obj.name===values.name && obj.password===values.password);
console.log(status==true?"Login Success":"Login Failed");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.