JavaScript Object keys() method returns an array of a given object’s own enumerable property names. The ordering of the properties is the same as that given by the object manually in a loop applied to the properties.
Object.keys(obj)
Where obj
is the object whose properties you want to return.
JavaScript object keys
A simple example code gets all keys of a given object.
<!DOCTYPE html>
<html>
<body>
<script>
var obj = {name: "Martin", age: 30, city: "United States"};
let res = Object.keys(obj);
console.log(res);
</script>
</body>
</html>
Output:
The Object.keys() function is a useful tool for iterating over the properties of an object. It can be used to loop through the properties of an object, or to filter the properties of an object based on certain criteria.
Here are some examples of how the Object.keys() function can be used:
Loop through the properties of an object:
const person = {
name: "John Doe",
age: 30,
address: "123 Main Street"
};
for (const key of Object.keys(person)) {
console.log(key);
}
Filter the properties of an object based on a certain criteria:
const person = {
name: "John Doe",
age: 30,
address: "123 Main Street"
};
const filteredKeys = Object.keys(person).filter(key => key === "name");
console.log(filteredKeys); // ["name"]
Comment if you have any doubts or suggestions on this Js Object key topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version