archytect archytect - 7 months ago 10
Javascript Question

Deleting items from javascript array results in error

I'm trying to loop through items within an object and removing items with the property delete whose value is true to then post that object as data.

when I use splice to remove an item, I get an Uncaught TypeError: Cannot read property 'delete' of undefined error. Why is that?

https://jsfiddle.net/ah9td94q/3/

var data = {
"stuff":[
{"x":0},
{"y":1, "delete": true},
{"z":2, "delete": true}
]
}

Object.keys(data.stuff).forEach(function (key) {
if (data.stuff[key].delete == true) {
data.stuff.splice(key, 1);
}
});

var postData = JSON.stringify({something:'something', data: data});
console.log(postData);



Answer
var data = {
    "stuff":[
        {"x":0},
        {"y":1, "delete": true},
        {"z":2, "delete": true}
    ]
}

Object.keys(data.stuff).reverse().forEach(function (key) {
    if (data.stuff[key].delete == true) {
    data.stuff.splice(key, 1);
  }
});

var postData = JSON.stringify({something:'something', data: data});
console.log(postData);

https://jsfiddle.net/ah9td94q/4/

You can't delete from an array counting forwards, because the elements after a deleted element will "move in" to the slot you just removed from. So, instead of removing from beginning to end, we remove from end to beginning, and circumvent this index issue.

Comments