For JavaScript Object, in order to get keys, values, and entries we use Object.keys
, Object.values
, and Object.entries
.
Object.keys(obj)
– returns all the keys of object as arrayObject.values(obj)
– returns all the values of the object as arrayObject.entries(obj)
– returns an array of [key, value]Let’s say we have a user Object:
let user ={
name : "Balaji",
age : 23,
greet : () => "Hello",
};
Use Object.keys
to get the keys of the Object:
let keys = Object.keys(user);
keys; //["name", "age", "greet"]
Object.keys
will return the keys that are available in the object while calling the function – any new keys added after this will not be updated:
let keys = Object.keys(user);
keys; //["name", "age", "greet"]
user.weight = 65;
// weight key will not be added to keys array
keys; //["name", "age", "greet"]
Use Object.values
to get the values of the Object:
let values = Object.values(user);
values; // ["Balaji", 23, ƒ, 65]
Use Object.entries
to get the [key, value] pair of the Object:
let entries = Object.entries(user);
entries;
// output
[ ["name", "Balaji"], ["age", 23], ["greet", ƒ], ["weight", 65] ]
You can use Object.entries
to get Object key, value pair, and use array methods like map, filter, and reduce:
let user ={
name : "Balaji",
age : 23,
};
let entries = Object.entries(user)
let data = entries.map( ([key, val] = entry) => {
return `The ${key} is ${val}`;
});
data; // ["The name is Balaji", "The age is 23"]
Note:
- When using the
Object.keys
, symbolic keys are not returned. Instead, useReflect.ownKeys(obj)
to returns all keys; or, useObject.getOwnPropertySymbols
to only get symbolic keys.
RELATED TAGS
CONTRIBUTOR
View all Courses