Reputation: 6049
I have an array of the object users
.
"users" : [
{
fname: "subrato",
lname:"patnaik",
password:"123"
},
{
fname: "john",
lname:"doe",
password:"123"
}
]
I want to check whether the above JSON data contain the below object.
{fname:"subrato", password:"123"}
How could we do that in Javascript?
Upvotes: 0
Views: 56
Reputation: 4156
Array.includes compares by object identity just like obj === obj2, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some() instead which takes a function:
let users = [
{
fname: "subrato",
lname:"patnaik",
password:"123"
},
{
fname: "john",
lname:"doe",
password:"123"
}
]
console.log(users.some(item => item.fname === 'subrato' && item.password === "123"))
Upvotes: 2
Reputation: 3302
Use JavaScript some function and it will return true if the object is found.
let users = [
{
fname: "subrato",
lname: "patnaik",
password: "123",
},
{
fname: "john",
lname: "doe",
password: "123",
},
];
let check = users.some((x) => x.fname === "subrato" && x.password === "123");
console.log(check);
Upvotes: 3
Reputation: 132
You're gonna need to loop through the array and do a check for it.
arr.forEach(obj => {
if(obj.fname == 'name' && obj.password == 'password') {
// Do stuff
}
})
Upvotes: 2