Home > Software engineering >  Checking for the existence of an element in array full of objects
Checking for the existence of an element in array full of objects

Time:05-24

I have an array of likes which includes the ids of the users that have liked the post (this is originally a mongoose model). I want to check if the user's id is in the array.

const likes =  
[
    {
        "user": "6283986e931a243f64eb063e"
    },
    {
        "user": "6283986e931a243f64eb0123s"
    },
]

const user = "6283986e931a243f64eb063e";

const hasBeenLiked = Object.values(likes).includes(user);

console.log(hasBeenLiked) //returns false

Obviously i cannot check this way. I am aware that i can do this with loop, but i want more lightweight approach (if possible).

The orignal code is:

const hasBeenLiked = Object.values(article.likes).includes(req.headers.user);

If this is not possible without the use of loops is there a mongoose command for this?

CodePudding user response:

Use Array.prototype.some()

const hasBeenLiked = likes.some(like => like.user === user);

CodePudding user response:

You can do it like that:

const hasBeenLiked = !!likes.find(l => l.user == user)

  • Related