user1005310 user1005310 - 3 months ago 26
JSON Question

Nested JSON, remove object based on a condition in Jquery using angularjs

I have a JSON object in this variable $scope.bbTreeData. I am trying to remove the object where flag is false. I am able to traverse through the nested JSON object but I am not sure how to remove the object ? any suggestion ?

[{
"market": "Atl",
"subItem": [{
"comment_id": "1",
"user_id": "32509",
"flag": true
}, {
"comment_id": "2",
"user_id": "32510",
"flag": false

}]
}, {
"market": "Chicago",
"subItem": [{
"comment_id": "3",
"user_id": "32501",
"flag": true
}, {
"comment_id": "4",
"user_id": "32502",
"flag": false

}]
}]

$scope.bbTreeInactiveData = angular.copy($scope.bbTreeData);
angular.forEach($scope.bbTreeInactiveData, function(item) {
angular.forEach(item.subItem, function(record, index) {
if (record.flag == false) {
console.log(item.subItem, index);
/* code to remove the object*/
}
});
});

rD. rD.
Answer

You can use _without() function of _underscorejs

see the documentation

without
_.without(array, values)

Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

Input

[
    {
        "market": "Atl",
        "subItem": [
            {
                "comment_id": "1",
                "user_id": "32509",
                "flag": true
            },
            {
                "comment_id": "2",
                "user_id": "32510",
                "flag": false
            }
        ]
    },
    {
        "market": "Chicago",
        "subItem": [
            {
                "comment_id": "3",
                "user_id": "32501",
                "flag": true
            },
            {
                "comment_id": "4",
                "user_id": "32502",
                "flag": false
            }
        ]
    }
]

Output

[
    {
        "market": "Atl",
        "subItem": [
            {
                "comment_id": "1",
                "user_id": "32509",
                "flag": true
            }
        ]
    },
    {
        "market": "Chicago",
        "subItem": [
            {
                "comment_id": "3",
                "user_id": "32501",
                "flag": true
            }
        ]
    }
]

Code Snippet

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

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));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>