-
Notifications
You must be signed in to change notification settings - Fork 2
Object.getOwnPropertyNames
The Object.getOwnPropertyNames()
method returns an array of all properties (enumerable or not) found directly upon a given object.
Object.getOwnPropertyNames(obj)
obj
The object whose enumerable and non-enumerable own properties are to be returned.
Object.getOwnPropertyNames()
returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly upon object. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a for...in
loop (or by Object.keys()
) over the properties of the object. The ordering of the non-enumerable properties in the array, and among the enumerable properties, is not defined.
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]);
});
// logs
// 0 -> a
// 1 -> b
// 2 -> c
// non-enumerable property
var my_obj = Object.create({}, {
getFoo: {
value: function() { return this.foo; },
enumerable: false
}
});
my_obj.foo = 1;
console.log(Object.getOwnPropertyNames(my_obj).sort()); // logs 'foo,getFoo'
function Pasta(grain, size, shape) {
this.grain = grain;
this.size = size;
this.shape = shape;
}
var spaghetti = new Pasta("wheat", 2, "circle");
var names = Object.getOwnPropertyNames(spaghetti).filter(CheckKey);
document.write(names);
// Check whether the first character of a string is 's'.
function CheckKey(value) {
var firstChar = value.substr(0, 1);
if (firstChar.toLowerCase() == 's')
return true;
else
return false;
}
// Output:
// size,shape
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links