Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js - Delete item from nested array?

I have the following object array:

var list = [{
  "id": 119,
  "files": []
}, {
  "id": 126,
  "files": [{
    "id": 9,
    "filename": "test1.docx",
  }, {
    "id": 10,
    "filename": "test2.docx",
  }]
}]

How can update the list by deleting the file with a specific id (file ids are unique) So for example I want to delete the file with id of 10 .

This is what I've tried so far using underscore but it doesnt work:

_.each(list.item, function(item, idx) {
  if (_.findWhere(item.files, { id: 10 })) {
    //remove file from files array
    files.splice(idx, 1); 
  }
});

I want to update the list by deleting file object with a particular id

All the solutions so far create a copy of the original. Is there any way to simply splice it out from the original list?

like image 360
adam78 Avatar asked Apr 26 '26 11:04

adam78


1 Answers

You can in fact do it completely without underscore:

var list = [{"id": 119, "files": []}, {"id": 126, "files": [{"id": 9, "filename": "test1.docx"}, {"id": 10, "filename": "test2.docx", }]}]

var itemId = 126
var fileId = 10

var out = list.map(function(item) {
    if (item.id === itemId) {
        // Copy the item in order to not mutate the original object
        var itemCopy = Object.assign({}, item)
        itemCopy.files = itemCopy.files.filter(function(file) { return file.id !== fileId })
        return itemCopy
    } else return item
})

console.log(out)
    
like image 128
TimoStaudinger Avatar answered Apr 28 '26 00:04

TimoStaudinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!