-1

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);
archytect
  • 3,615
  • 5
  • 22
  • 30
  • 1
    [Related, maybe dupe?](http://stackoverflow.com/questions/500606/javascript-array-delete-elements) Note that you're trying to remove items in an array, not delete properties from an object. – James Thorpe Apr 29 '16 at 15:46
  • 1
    `delete()` does that to arrays making them sparse and difficult to deal with. I believe the reason why we need that type of behavior is if there was partial data and you needed to fill empty areas of a table. Use `pop` or `shift`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Deleting_array_elements – zer00ne Apr 29 '16 at 15:48
  • When you use the delete keyword to remove an element from an array, it is actually replaced with a null value. This is what's happening in your situation. See [this answer](http://stackoverflow.com/a/12469043/5423708) for a better explanation. It offers a solution, but make sure to look at the comments as well for more context. – mr_schmiggles Apr 29 '16 at 16:03

1 Answers1

3
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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
aaronofleonard
  • 2,546
  • 17
  • 23