0

i wanted to delete index from array if rest service response return true , so in below case lets say we have true from rest service i wanted to delete object where id is 'RA_ATTST_LANGUAGE` from array. I tried below code but its not deleting what is missing ?

main.js

MessageAdminNotificationFactory.getAttestationLanValidation().then(function(response){
        var data = response.data;
        console.log('attestation',data);
        if(data){
          angular.forEach($scope.adminDataSource,function(value,$index){
            if(value.id === 'RA_ATTST_LANGUAGE'){
              $scope.adminDataSource.splice($index, 1);
            }
            console.log('dropdown',value.id);
          });
        }
      });

$scope.adminDataSource = [{
    "uid": null,
    "index": 0,
    "selected": null,
    "expanded": null,
    "id": "RA_PLTFRM_NOTIF",
    "text": "Platform Maintenance Notification",
    "parentId": null,
    "items": null
}, {
    "uid": null,
    "index": 0,
    "selected": null,
    "expanded": null,
    "id": "RA_ATTST_LANGUAGE",
    "text": "Attestation Language",
    "parentId": null,
    "items": null
}]
2
  • you're modifying an array as you iterate over its index. Not sure if that is the cause but you should never do that. at least break the loop if you do. But you should prob use Array.filter Commented May 18, 2016 at 20:08
  • This really has nothing to do with angular Commented May 18, 2016 at 20:23

2 Answers 2

0
$scope.adminDataSource = $scope.adminDataSource.filter(
  function(value){
     return value.id !== 'RA_ATTST_LANGUAGE';
})

Array.filter is the way to go. filters out anything that evaluates to false;

Sign up to request clarification or add additional context in comments.

Comments

0

Iterate the array from end to start

for(var i=$scope.adminDataSource.length-1;i>=0;i--){
    var value = $scope.adminDataSource[i];
    if(value.id === 'RA_ATTST_LANGUAGE') {
       $scope.adminDataSource.splice(i,1);
    }
}

This way it doesn't matter if the array shrinks while you iterate.

3 Comments

Avoid using let if question is not tagged es6?
You're right. Just a typescript habit of mine. TS transpiles let into var.
and now stack overflow has 3 more questions... let? es6? typescript? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.