[英]remove elements from nested object array
我想使用angularjs / jQuery从JSON对象中基于条件检查删除对象。 我尝试使用下面的代码,但输出不符合预期。
演示: https : //plnkr.co/edit/EWwbETITqn7G79Xypt0g?p = preview
angular.module('ui.bootstrap.demo').controller('DataCtrl', function ($scope) {
$scope.responseData = {
"data": [{
"name": "Machine", "quantity": 20, "snVal": 22,
"machine1": [{ "id": 2009, "machineName": "ASD1", "trackID": "34219", "status": "delivered" },
{ "id": 27893, "machineName": "PX20AA", "trackID": "3422", "status": "avail" }],
"machine2": [{ "id": 1023, "machineName": "XY22", "trackID": "1345", "status": "avail" },
{ "id": 1233, "machineName": "PP3DF", "trackID": "112", "status": "delivered" }
]
}]
}
console.log("R1 :: " + JSON.stringify($scope.responseData));
$scope.newResponse = $.grep($scope.responseData.data, function (element, index) { return element.status == "delivered" }, true);
console.log("R2 after removing elements:: " + JSON.stringify($scope.newResponse));
});
尝试这个,
let responseData = { "data": [{ "name": "Machine", "quantity": 20, "snVal": 22, "machine1": [{ "id": 2009, "machineName": "ASD1", "trackID": "34219", "status": "delivered" }, { "id": 27893, "machineName": "PX20AA", "trackID": "3422", "status": "avail" }], "machine2": [{ "id": 1023, "machineName": "XY22", "trackID": "1345", "status": "avail" }, { "id": 1233, "machineName": "PP3DF", "trackID": "112", "status": "delivered" }] }] } ; let newResponse = responseData; newResponse.data.forEach(function (item) { for (j in item) { if (j.includes("machine")) { //better you check if type is array, using Object.prototype.toString.call(j) === "[object Array]" item[j] = item[j].reduce(function (acc, machine) { if (machine.status !== "delivered"){ acc.push(machine); } return acc; }, []); } } })| console.log(newResponse);
在这里,我们只是遍历数据字段中的所有对象。 由于诸如machine1,machine2之类的属性是一个数组,因此我们对其进行迭代并过滤所有未交付的计算机。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.