简体   繁体   中英

remove elements from nested object array

I want to remove object based on conditional check from the JSON object using angularjs/jQuery. I tried with below code but output is not as expected.

Demo: 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));
});

Try this,

 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); 

Here we are just iterating through all objects in the data field. Since properties like machine1, machine2 is an array, we iterate through it and filter all machines which are not delivered.

You must note that I have used a for-in loop and array reduce() method here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM