I have an object with various properties. The name of the object is a global variable but the properties are changed at runtime by methods. Some methods add properties to the object. I’d like to add a method that loops through this object and removes all of its properties that are either null or empty. I could check each property by specifying its name and checking its state but if I add properties later, I’d have to update this cleanup method too. How can I loop through the properties of an object without know the name of the properties first.
Thanks for your suggestions.
Iteration over an object is simple – the
for inloop:isEmptydoesn’t exist, you have to define it or replace it with something more meaningful, I couldn’t understand what you meant by empty in your question.I use
object.hasOwnPropertybecause objects inherit things fromObject.prototypeand possibly other places (arrays for example inherit fromArray.prototype, which inherits fromObject.prototype). So:But,
object.toStringactually refers toObject.prototype.toString– it isn’t really in your object, but when you typeobject.toString, the interpreter sees that there’s noobject.toString, so it checks up the prototype chain until it finds it.hasOwnPropertychecks if a key actually exists on an object:Subscript access to objects is also simple:
Note that whatever is passed to the brackets gets converted to a string. So, for example, you can do this:
In case you’re wondering, Object.keys is an ES5 (EcmaScript 5) feature.