hello javascript heroes. i been suffering from this issue long time. the problem is that i'm searching inside an object using object as a key of search also using filter method. like this
let data = [
{
name:"Jade",
role:"admin",
pass:"0000"
},
{
name:"Jon",
role:"user",
pass:"0000"
},
{
name:"Adam",
role:"user",
pass:"0000"
},
]
let result = data.filter((item)=>{
return {role:"user",pass:"0000"} in item
})
i also tried
let result = data.filter((item)=>{
return {role:"user",pass:"0000"} in {...item}
})
it always return an empty array.
please let me know if there is any way to solve this
CodePudding user response:
You cant simply compare objects using "in" operator. You can iterate the whole object and match values. Or simply match all values in objects.
**Sample **
let data = [
{
name: "Jade",
role: "admin",
pass: "0000",
},
{
name: "Jon",
role: "user",
pass: "0000",
},
{
name: "Adam",
role: "user",
pass: "0000",
},
];
//1: Matching whole object
const isEqual = (user, item) => {
return Object.entries(user).every(([key, value]) => item[key] === value);
};
let result = data.filter((item) => {
return isEqual({ role: "user", pass: "0000" }, item);
});
console.log(result);
// 2: Matching values
const isEqua2 = (user, item) =>
user.role === item.role && user.pass === item.pass;
let result2 = data.filter((item) => {
return isEqua2({ role: "user", pass: "0000" }, item);
});
console.log(result2);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could read up on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes you could for exemple do and if statment of sort
CodePudding user response:
do it like that :
let result = data.filter((item)=>{
return item.role == "user" && item.pass == "0000";
})
CodePudding user response:
I think you can cover up the case by using true/false, as your title says to check if an object exists in the data.
function check(obj, data) {
for (let i = 0; i < data.length; i ) {
if (obj.name === data[i].name) {
return true;
}
}
return false;
}
In which if you try
console.log(check({ name: 'Jade', role: 'admin', pass: '0000' }, data));
would return true
.