Object.keys() / values() / entries() Since: ES5(ECMAScript 2009)
Retrieves an object's key names, values, or key-value pairs as an array.
Syntax
// Returns an array of the object's key names. Object.keys(object) // Returns an array of the object's values. Object.values(object) // Returns an array of the object's key-value pairs. Object.entries(object)
Method List
| Method | Description |
|---|---|
| Object.keys(object) | Returns an array of strings containing the enumerable property key names of the object. |
| Object.values(object) | Returns an array of the enumerable property values of the object. |
| Object.entries(object) | Returns an array of [key, value] pairs for each enumerable property of the object. |
Sample Code
var user = {
name: "Kuu",
age: 25,
city: "Tokyo"
};
// Get an array of key names.
console.log(Object.keys(user)); // Outputs ["name", "age", "city"].
// Get an array of values.
console.log(Object.values(user)); // Outputs ["Kuu", 25, "Tokyo"].
// Get an array of key-value pairs.
console.log(Object.entries(user)); // Outputs [["name", "Kuu"], ["age", 25], ["city", "Tokyo"]].
// You can loop over keys using Object.keys with forEach.
Object.keys(user).forEach(function(key) {
console.log(key + ": " + user[key]);
});
// You can also loop using Object.entries with destructuring.
Object.entries(user).forEach(function([key, value]) {
console.log(key + " = " + value);
});
// You can get the number of properties.
console.log(Object.keys(user).length); // Outputs 3.
Overview
Object.keys(), Object.values(), and Object.entries() are methods that retrieve an object's property information as arrays. Unlike a for...in loop, they do not include properties from the prototype chain, so you can safely retrieve only the object's own properties.
Because the return value is an array, you can combine these methods with array methods such as forEach(), map(), and filter() for flexible processing. To count the number of properties, Object.keys(obj).length is convenient and can also be used to check whether an object is empty.
Object.entries() works well with for...of loops and destructuring assignment to process both keys and values efficiently. To convert an array of key-value pairs back into an object, use Object.fromEntries().
Browser Compatibility
4 or earlier ×
3.5 or earlier ×
4 or earlier ×
8 or earlier ×
11 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.