Categories
Other

Remove undefined from a Javascript object

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.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.

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

Comments are closed.