Petter Östergren
Petter Östergren

Reputation: 1013

Check if an Object Key has a property if so, check .length on values

How do I check if an Object has a certain key and then count the amount of "values" that key has?

enter image description here

(Image displays: numberOfComments object)

I want to check against post.id so something like.

if (post.id === Object.keys(numberOfComments) {
   const numOfComment = (numberOfComments Value).length

   return numOfComment

} else if (post.id !== Object.keys(numberOfComments) { 
   const numOfComment = 0
   return numOfComment
}

Should return 2 for this case. One important feature, of course, is that it needs to be dynamic. The post.id is not always the same.

The meaning of this is to return an object from Redux store check if a post has any comments and if so display the number of comments.

Thank you!

Upvotes: 0

Views: 929

Answers (2)

isijara
isijara

Reputation: 155

You can do it this way

First you check if your object contains the value of post.id in its keys, then if that's true you get the value from numberOfComments[post.id] and return its length, otherwise the post.id was not found and you return 0.

if(Object.keys(numberOfComments).indexOf(post.id)) {
  return numberOfComments[post.id].length;
} else {
 return 0;
}

cheers

Upvotes: 0

Brian Glaz
Brian Glaz

Reputation: 15676

If you want to check if an object has a property, you can just use if( obj[property]). In your case, you could easily condense your code above in to one line.

return (numberOfComments[post.id] ? numberOfComments[post.id].length : 0);

Upvotes: 2

Related Questions