0

I am using Underscore.js in my project and came across a weird behavior. When I filter the array with changes_summary === 2 I am getting the desired result but when I use the same with changes_summay === 0, I am not getting any output.

Following is the code:

var result={
   "data": [
     {
      "id": 956,
      "changes_summary": 2,
      "name": "Pradeep",
      "age": 32
     },
     {
      "id": 956,
      "changes_summary": 0,
      "name": "praveen",
      "age": 22
     }
  ]
}


var filtered = _.filter(result.data, function(obj){ 
    return (obj.changes_summary && obj.changes_summary === 2)
});
//working when comparing with changes_summary with 2 but not working when comparing with 0
console.log(filtered);

Please let me know where I am going wrong. Link to Jsfiddle attached: Jsfiddle

2
  • obj.changes_summary && remove this to check for 0. 0 is falsy See jsfiddle.net/tusharj/2j13o0be/1 Commented Jul 22, 2015 at 13:30
  • @Tushar removing it is not necessarily the right thing. If the filter is only supposed to apply to objects that definitely have the property, then an additional test is necessary. Commented Jul 22, 2015 at 13:31

1 Answer 1

1

The first test — obj.changes_summary — will fail when the property value is 0 because that's a falsy value. If you're testing to see if the property is present in the object, you can do this:

return (("changes_summary" in obj) && obj.changes_summary === 0);
Sign up to request clarification or add additional context in comments.

2 Comments

Is the in even needed?
@muistooshort well it depends on the intention - if the idea is to filter out objects that definitely have the property and for which the property value is 0, then it's necessary. If objects without the property should be treated as if the property value is 0, then no.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.