How to iterate through property names of Javascript object?

后端 未结 2 1342
忘了有多久
忘了有多久 2020-11-30 21:26

I would like to get the property names from a Javascript object to build a table dynamically. Example:

var obj = {\'fname\': \'joe\', \'lname\': \'smith\',          


        
相关标签:
2条回答
  • 2020-11-30 21:40

    Use for...in loop:

    for (var key in obj) {
       console.log(' name=' + key + ' value=' + obj[key]);
    
       // do some more stuff with obj[key]
    }
    
    0 讨论(0)
  • 2020-11-30 21:58

    In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

    Object.getOwnPropertyNames ( obj )
    

    and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

    Object.keys( obj )
    

    I used forEach to list values and keys in obj, same as for (var key in obj) ..

    Object.keys(obj).forEach(function (key) {
          console.log( key , obj[key] );
    });
    

    This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

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