Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm working with AngularJS and have an object array like that in my controller :

$scope.folderList = [{
    name: 'root',
    path: 'uploads/',
    subs: [{
        name: 'pictures',
        path: 'uploads/pictures',
        subs: [{
            ...
        }]
    }, {
        name: 'videos',
        path: 'uploads/videos',
        subs: [{
            ...
        }]
    }]
}];

For this nested array, I have 2 directives set them up in a nested UL LI list with ng-repeat.

Now I have my nested list of folders, and I want to trigger a function to delete the selected folder.

So I trigger my function to delete with "folder" in parameter, for example, if I trigger the "delete" function on the pictures folder, the folder parameter will be like that :

folder = {
    name: 'pictures',
    path: 'uploads/pictures',
    subs: [{ ... }]
}

And I want to delete this object from the nested array.

With a 1 level object array, I use this :

var index = $scope.folderList.indexOf(folder);
delete $scope.folderList.splice(index, 1);

But it (obviously) doesn't work on a nested array !

How can I easily delete an entry from a nested array on JavaScript (or AngularJS ?)

I've heard that underscore.js was made for this, but I never used it, and after seeing their documentation I wasn't able to find the proper function to do this !

Thanks for your help !

share|improve this question
    
You will need to write a recursive function over subs for this. You may also need to think how you'll perform your compare if the search parameter folder is an identical Object but not the same reference. –  Paul S. Sep 2 '13 at 11:42
    
Thanks for your reply ! I could use the "path" to get where I want to be. Then i'll have several index of each parent folders ? (For example, to go on the "pictures" folder, I'll have [0, 0]). But, I don't think I can do : "delete $scope.folderList.splice([0, 0], 1);" ? How can, if I have all indexes to go to the right folder, delete the right folder from those indexes ? Can I use splice ? Or is there another function for that ? –  Max Leroux Sep 2 '13 at 11:53
    
You still use splice, but you use the correct this to call it on var cd = $scope.folderList; cd = cd[0]; cd.splice(0, 1); –  Paul S. Sep 2 '13 at 12:02
    
Thanks ! It worked, and was easier than I thought and quite obvious for the splice, now that I saw it ! –  Max Leroux Sep 2 '13 at 21:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.