我在这个变量 $scope.bbTreeData 中有一个 JSON 对象。我正在尝试删除标志为假的对象。我能够遍历嵌套的 JSON 对象,但我不确定如何删除该对象?有什么建议吗?
[{
"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*/
}
});
});
最佳答案
您可以使用_underscorejs 的_without()
函数
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]
输入
[
{
"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
}
]
}
]
输出
[
{
"market": "Atl",
"subItem": [
{
"comment_id": "1",
"user_id": "32509",
"flag": true
}
]
},
{
"market": "Chicago",
"subItem": [
{
"comment_id": "3",
"user_id": "32501",
"flag": true
}
]
}
]
代码片段
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>
关于javascript - 嵌套的 JSON,使用 angularjs 根据 Jquery 中的条件删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39127325/