I’ve been doing a fair amount of javascript programming lately, and I found myself needing to remove a nested object from an object. Doing this is easy enough with the “delete” command, but it leaves you with annoying “undefined”s all over. To get around that, I scoured the internet for a way to remove them easily. Turns out that if efficiency isn’t a problem, it’s easier to drop the right objects into an array and then re-assign it.
var tmpArray = new Array(); for(el in self.orderData.data.items) { if(self.orderData.data.items[el]) { tmpArray.push(self.orderData.data.items[el]); } } self.orderData.data.items = tmpArray; |
Easy and pie.
2 replies on “Remove undefined from a Javascript object”
Thanks! Exactly what I was looking to do instead of trying to use splice. Works perfectly. 🙂
Thank you! This helped me a lot, but it was not so easy to find this page. 🙂