user1005310 user1005310 - 3 months ago 19
jQuery Question

filtering nested JSON underscore

This is the jsfiddle

https://jsfiddle.net/sal1681/2043fumn/

When I execute the code, it returns one subitem for market ATL, in actuality it should not return anything for subitem ATL since I am filtering by flag which is set to false.

Here is the code

var json = JSON.parse('[
{
"market": "Atl",
"subItem": [
{
"comment_id": "1",
"flag": false,
"user_id": "32509"
},
{
"comment_id": "2",
"flag": false,
"user_id": "32510"
}
]
},
{
"market": "Chicago",
"subItem": [
{
"comment_id": "3",
"flag": true,
"user_id": "32501"
},
{
"comment_id": "4",
"flag": false,
"user_id": "32502"
}
]
}
]');

for(var i=0; i<json.length; i++) {
json[i].subItem = _.without(json[i].subItem, _.findWhere(json[i].subItem, {flag: false}));
};

console.log(JSON.stringify(json, 0, 8));

Answer

The problem you're having is that findWhere only returns the first value that matches, not a list of the matching values.

A better option is probably to use the filter function.

for (var i = 0; i < json.length; i++) {
  json[i].subItem = _.filter(json[i].subItem, function(subItem) {
    return subItem.flag;
  });
}
Comments