To get all properties that belong to an object in javascript, we can use Object.getOwnPropertyNames(). The ordering of the non-enumerable properties in the array, and among the enumerable properties, is not defined.
Example:
var arr = ['a', 'b', 'c'];
console.log(Object.getOwnPropertyNames(arr).sort()); // logs '0,1,2,length'
// Array-like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort()); // logs '0,1,2'
// Logging property names and values using Array.forEach
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
console.log(val + ' ---; ' + obj[val]);
});
// non-enumerable property
var myobj = Object.create({}, {
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
myobj.foo = 1;
console.log(Object.getOwnPropertyNames(myobj).sort());
0 Comment(s)