Reputation: 877
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*/
}
});
});
Upvotes: 1
Views: 1765
Reputation: 4597
Try this:
$scope.bbTreeInactiveData = angular.copy($scope.bbTreeData);
var results = $scope.bbTreeInactiveData.map(function(row) {
return row.subItem.filter(function(cell) {
return cell.flag == true
});
});
Use map() and filter() function.
Upvotes: 1
Reputation: 6652
You can use the delete
keyword in plain JavaScript:
delete item.subItem[index]
Which I believe there is already an answer for: How do I remove a property from a JavaScript object?
If you want to delete the root, add an index parameter to your first forEach
, then delete the root with array splice function:
$scope.bbTreeInactiveData.splice(indexRoot,1);
Upvotes: 0
Reputation: 31851
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>
Upvotes: 2