How to list the properties of a JavaScript object?

后端 未结 17 2574
刺人心
刺人心 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:19

    I'm a huge fan of the dump function.

    http://ajaxian.com/archives/javascript-variable-dump-in-coldfusion alt text

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

    In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

    var keys = Object.keys(myObject);
    

    The above has a full polyfill but a simplified version is:

    var getKeys = function(obj){
       var keys = [];
       for(var key in obj){
          keys.push(key);
       }
       return keys;
    }
    

    Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

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

    IE does not support for(i in obj) for native properties. Here is a list of all the props I could find.

    It seems stackoverflow does some stupid filtering.

    The list is available at the bottom of this google group post:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0

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

    Note that Object.keys and other ECMAScript 5 methods are supported by Firefox 4, Chrome 6, Safari 5, IE 9 and above.

    For example:

    var o = {"foo": 1, "bar": 2}; 
    alert(Object.keys(o));
    

    ECMAScript 5 compatibility table: http://kangax.github.com/es5-compat-table/

    Description of new methods: http://markcaudill.com/index.php/2009/04/javascript-new-features-ecma5/

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

    Since I use underscore.js in almost every project, I would use the keys function:

    var obj = {name: 'gach', hello: 'world'};
    console.log(_.keys(obj));
    

    The output of that will be:

    ['name', 'hello']
    
    0 讨论(0)
  • 2020-11-22 01:27

    With ES6 and later (ECMAScript 2015), you can get all properties like this:

    let keys = Object.keys(myObject);
    

    And if you wanna list out all values:

    let values = Object.keys(myObject).map(key => myObject[key]);
    
    0 讨论(0)
提交回复
热议问题