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?

Amir
  • 1,219
  • 3
  • 17
  • 31

4 Answers4

13

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
  • 6,390
  • 2
  • 22
  • 17
  • 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 Jul 31 '09 at 21:53
  • When you iterate a string, it will step through each character. Try passing String(s) instead, to wrap the string in an object. – devios1 Jun 24 '11 at 14:52
6

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

Community
  • 1
  • 1
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
3

This only works in modern browsers (Chrome, Firefox 4+, IE9+), but in ECMAScript 5, you can 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
  • 101,441
  • 24
  • 103
  • 129
0

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
  • 276
  • 2
  • 2