The Object.getOwnPropertyNames function provides an array containing all properties associated directly with a specified object, excluding any non-enumerable properties that utilize symbols.
Syntax:
Example
Object.getOwnPropertyNames(obj)
Parameter:
obj : This refers to the object from which both its enumerable and non-enumerable own properties will be retrieved.
Return value:
This approach yields an array of strings that represent the properties located directly on the object.
Browser Support:
| Chrome | 5 |
|---|---|
Edge |
Yes |
| Firefox | 4 |
| Opera | 12 |
Example 1
Example
const object1 = {
a: 0,
b: 1,
c: 2,
};
console.log(Object.getOwnPropertyNames(object1));
Output:
Output
["a", "b", "c"]
Example 2
Example
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]);
});
Output:
Output
["0", "1", "2"]
"0 -> a"
"1 -> b"
"2 -> c"
Example 3
Example
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:
Output
size,shape