How to list the properties of a JavaScript object?

后端 未结 17 2573
刺人心
刺人心 2020-11-22 00:34

Say I create an object thus:

var myObject =
        {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};

What is

相关标签:
17条回答
  • 2020-11-22 01:10

    if you are trying to get the elements only but not the functions then this code can help you

    this.getKeys = function() {
    
        var keys = new Array();
        for(var key in this) {
    
            if( typeof this[key] !== 'function') {
    
                keys.push(key);
            }
        }
        return keys;
    }
    

    this is part of my implementation of the HashMap and I only want the keys, "this" is the hashmap object that contains the keys

    0 讨论(0)
  • 2020-11-22 01:12

    Object.getOwnPropertyNames(obj)

    This function also shows non-enumerable properties in addition to those shown by Object.keys(obj).

    In JS, every property has a few properties, including a boolean enumerable.

    In general, non-enumerable properties are more "internalish" and less often used, but it is insightful to look into them sometimes to see what is really going on.

    Example:

    var o = Object.create({base:0})
    Object.defineProperty(o, 'yes', {enumerable: true})
    Object.defineProperty(o, 'not', {enumerable: false})
    
    console.log(Object.getOwnPropertyNames(o))
    // [ 'yes', 'not' ]
    
    console.log(Object.keys(o))
    // [ 'yes' ]
    
    for (var x in o)
        console.log(x)
    // yes, base
    

    Also note how:

    • Object.getOwnPropertyNames and Object.keys don't go up the prototype chain to find base
    • for in does

    More about the prototype chain here: https://stackoverflow.com/a/23877420/895245

    0 讨论(0)
  • 2020-11-22 01:13

    Use Reflect.ownKeys()

    var obj = {a: 1, b: 2, c: 3};
    Reflect.ownKeys(obj) // ["a", "b", "c"]
    

    Object.keys and Object.getOwnPropertyNames cannot get non-enumerable properties. It's working even for non-enumerable properties.

    var obj = {a: 1, b: 2, c: 3};
    obj[Symbol()] = 4;
    Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]
    
    0 讨论(0)
  • 2020-11-22 01:14

    Could do it with jQuery as follows:

    var objectKeys = $.map(object, function(value, key) {
      return key;
    });
    
    0 讨论(0)
  • 2020-11-22 01:17

    Under browsers supporting js 1.8:

    [i for(i in obj)]
    
    0 讨论(0)
  • 2020-11-22 01:18

    As Sam Dutton answered, a new method for this very purpose has been introduced in ECMAScript 5th Edition. Object.keys() will do what you want and is supported in Firefox 4, Chrome 6, Safari 5 and IE 9.

    You can also very easily implement the method in browsers that don't support it. However, some of the implementations out there aren't fully compatible with Internet Explorer. Here's a more compatible solution:

    Object.keys = Object.keys || (function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"),
            DontEnums = [ 
                'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',
                'isPrototypeOf', 'propertyIsEnumerable', 'constructor'
            ],
            DontEnumsLength = DontEnums.length;
    
        return function (o) {
            if (typeof o != "object" && typeof o != "function" || o === null)
                throw new TypeError("Object.keys called on a non-object");
    
            var result = [];
            for (var name in o) {
                if (hasOwnProperty.call(o, name))
                    result.push(name);
            }
    
            if (hasDontEnumBug) {
                for (var i = 0; i < DontEnumsLength; i++) {
                    if (hasOwnProperty.call(o, DontEnums[i]))
                        result.push(DontEnums[i]);
                }   
            }
    
            return result;
        };
    })();
    

    Note that the currently accepted answer doesn't include a check for hasOwnProperty() and will return properties that are inherited through the prototype chain. It also doesn't account for the famous DontEnum bug in Internet Explorer where non-enumerable properties on the prototype chain cause locally declared properties with the same name to inherit their DontEnum attribute.

    Implementing Object.keys() will give you a more robust solution.

    EDIT: following a recent discussion with kangax, a well-known contributor to Prototype, I implemented the workaround for the DontEnum bug based on code for his Object.forIn() function found here.

    0 讨论(0)
提交回复
热议问题