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 Answers 4

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
Sign up to request clarification or add additional context in comments.

2 Comments

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);
When you iterate a string, it will step through each character. Try passing String(s) instead, to wrap the string in an object.
6

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

Comments

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);
        }
    }
}

Comments

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);

1 Comment

What if the property is a key for an object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.