I would like to get the property names from a Javascript object to build a table dynamically. Example:
var obj = {\'fname\': \'joe\', \'lname\': \'smith\',
Use for...in loop:
for (var key in obj) {
console.log(' name=' + key + ' value=' + obj[key]);
// do some more stuff with obj[key]
}
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.