JavaScript: Retrieve all the names of object's own and inherited properties
JavaScript Object: Exercise-13 with Solution
Write a JavaScript function to retrieve all the names of an object's own and inherited properties.
Sample Solution: -
JavaScript Code:
function allKeys(obj) {
if (!isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
function isObject(obj)
{
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
}
function Student(name) {
this.name = name;
}
Student.prototype.rollno = true;
console.log(allKeys(new Student("Sara")));
Output:
["name","rollno"]
Flowchart:
Live Demo:
See the Pen javascript-object-exercise-13 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to parse an URL.
Next: Write a JavaScript function to retrieve all the values of an object's properties.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-object-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics