Why Object.getOwnPropertyNames ?
Object.getOwnPropertyNames () returns the names of an object’s properties as an array. An object’s own properties are properties that are defined directly on that object and are not inherited from the prototype of the object.
Note that this is not a method to call on an object: it is a public function and you must pass it on to an object.
Syntax:
Object.getOwnPropertyNames( object )
- object (required): The object whose enumerable and non-enumerable own properties are to be returned.
Return Value:
- An array that contains the names of the own properties of the object.
JavaScript Object.getOwnPropertyNames Examples
Example 1
In the following example we did the following:
- We have defined a function called people.
- In this function, we have added parameters named “name, surname, age, from”.
- Then we created an arrow function called “print”. With this function, we returned the values we received.
- We created an object named person1 outside the function. And we entered the parameters.
- We created a variable called “Arr”. We’ve added this variable to the object named person1 by applying the Object.getOwnPropertyNames method.
- Last we printed the “Arr” variable.
function people(name, surname, age, from) {
this.name = name;
this.surname = surname;
this.age = age;
this.from = from;
this.print = () => {
return( "name: " + this.name +
"surname: " + this.surname +
"age: " + this.age +
"from: " + this.from)
}
}
let person1 = new people("rick", "quenn", 25, "England");
let arr = Object.getOwnPropertyNames(person1);
console.log(arr);
output:
[“name”, “surname”, “age”, “from”, “print”]
Example 2
let myObject = {
number1: 10,
number2: 20,
number3: 30
};
let arr = Object.getOwnPropertyNames(myObject);
console.log(arr);
output:
[“number1”, “number2”, “number3”]
Example 3
let numberList = {
4: "forth",
1: "first",
3: "third",
5: "fifth",
2:"second"
};
let arr = Object.getOwnPropertyNames(numberList).sort();
console.log(arr);
output:
[“1”, “2”, “3”, “4”, “5”]
Example 4
function ParentClass() { }
ParentClass.prototype.inheritedMethod = function () { };
function ChildClass() {
this.prop = 5;
this.method = function () { };
}
ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function () { };
console.log(
Object.getOwnPropertyNames(
new ChildClass() // ["prop", "method"]
)
);
output:
[“prop”, “method”]
Browser Support
| Chrome | 5 |
| Edge | yes |
| Firefox | 4 |
| Internet Explorer | 9 |
| Opera | 12 |
| Safari | 5 |
| Android webview | yes |
| Chrome for Android | yes |
| Edge mobile | yes |
| Firefox for Android | 4 |
| Opera Android | yes |