Iterate over object properties

There is a way to iterate over the properties and methods of an object. I need to write a utility function as follows:

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

so run this function:

iterate(String);

will print:

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

any ideas?

+3
source share
4 answers

See my answer to this other question , but you cannot read inline properties.

+6
source

It should be so simple:

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

Note. The function console.logassumes you are using firebug . At this stage:

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

iterate(obj);

will return:

number p1
string p2
function m1
+12
source

(Chrome, Firefox 4+, IE9 +), ECMAScript 5 Object.getOwnPropertyNames. .

// 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 properties
    var prototype = Object.getPrototypeOf(obj);
    if (prototype !== null) {
        getProperties(prototype, properties);
    }

    // Get obj 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);
        }
    }
}
+3
source

You can use the for loop to iterate over the properties of an object.

Here is a simple example

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

for(var p in o)
    alert(p);
0
source

Source: https://habr.com/ru/post/1714097/


All Articles