tags:

views:

398

answers:

4

is there a way to iterate an object properties and methods. i need to write a utility function like so:

function iterate(obj)
{
    //print all obj properties     
    //print all obj methods
}

so running this function:

iterate(String);

will print:

property: lenght
function: charAt
function: concat...

any ideas?

+4  A: 

See my answer in this other question, but you can't read built-in properties like that.

Peter Bailey
+3  A: 

Should be as simple as this:

function iterate(obj) {
    for (p in obj) {
        console.log(typeof(obj[p]), p);
    }
}

Note: The console.log function is assuming you are using firebug. At this point, the following:

obj = {
    p1: 1, 
    p2: "two",
    m1: function() {}
};

iterate(obj);

would return:

number p1
string p2
function m1
sixthgear
it seems that running your example works.However when i used the String class it didn't return anything. iterate(String);I also tried: var s = "sss";iterate(s);
Amir
A: 

You can use the for loop to iterate an object's properties.

Here is a simple example

var o ={'test':'test', 'blah':'blah'};

for(var p in o)
    alert(p);
Michael
A: 

This won't work in current browsers, but in ECMAScript 5, you will be able get all the properties of an object with Object.getOwnPropertyNames. It just takes a little extra code to get the inherited properties from the prototype.

// Put all the properties of an object (including inherited properties) into
// an object so they can be iterated over
function getProperties(obj, properties) {
    properties = properties || {};

    // Get the prototype's properties
    var prototype = Object.getPrototypeOf(obj);
    if (prototype !== null) {
        getProperties(prototype, properties);
    }

    // Get obj's own properties
    var names = Object.getOwnPropertyNames(obj);
    for (var i = 0; i < names.length; i++) {
        var name = names[i];
        properties[name] = obj[name];
    }

    return properties;
}

function iterate(obj) {
    obj = Object(obj);

    var properties = getProperties(obj);

    for (var name in properties) {
        if (typeof properties[name] !== "function") {
            console.log("property: " + name);
        }
    }
    for (var name in properties) {
        if (typeof properties[name] === "function") {
            console.log("function: " + name);
        }
    }
}
Matthew Crumley