Skip to content Skip to sidebar Skip to footer

Javascript Looping And Deleting Object Properties

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 objec

Solution 1:

Iteration over an object is simple - the for in loop:

for (var key inobject) {
    if (object.hasOwnProperty(key)) {
        //Now, object[key] is the current valueif (object[key] === null || isEmpty(object[key]))
            deleteobject[key];
    }
}

isEmpty doesn'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.hasOwnProperty because objects inherit things from Object.prototype and possibly other places (arrays for example inherit from Array.prototype, which inherits from Object.prototype). So:

object.toString; //function toString() { [native code] }

But, object.toString actually refers to Object.prototype.toString - it isn't really in your object, but when you type object.toString, the interpreter sees that there's no object.toString, so it checks up the prototype chain until it finds it.

hasOwnProperty checks if a key actually exists on an object:

object.hasOwnProperty("toString"); //falseobject.foo = "bar";
object.hasOwnProperty("foo"); //true

Subscript access to objects is also simple:

varobject = {foo: "bar"};
object.foo; //"bar"object["foo"]; //"bar"var key = "foo";
object[key]; //"bar"

Note that whatever is passed to the brackets gets converted to a string. So, for example, you can do this:

object[Object.prototype.toString] = "magic";

Object.keys(object); //["function toString() { [native code] }"]

In case you're wondering, Object.keys is an ES5 (EcmaScript 5) feature.

Solution 2:

You can use a for each loop to iterate through the object properties.

for ( var i in obj ) {
    if ( obj[i] === null ) {
        delete obj[i];
    }
}

Post a Comment for "Javascript Looping And Deleting Object Properties"