I have an object with several properties. I would like to remove any properties that have falsy values.
This can be achieved with compact on arrays, but what about objects?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could make your own underscore plugin (mixin) :
And then use it as a native underscore method :
Update
As @AndreiNeculau pointed out, this mixin affects the original object, while the original
compactunderscore method returns a copy of the array.To solve this issue and make our
compactObjectbehave more like it’s cousin, here’s a minor update: