Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
objects

How to get Keys, Values, and Entries in JavaScript Object?

Programming Bytes

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 array
  • Object.values(obj) – returns all the values of the object as array
  • Object.entries(obj) – returns an array of [key, value]

Let’s say we have a user Object:

let user ={
    name : "Balaji",
    age : 23,
    greet : () => "Hello",
};   

Get Keys of the Object

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"]

Get values of the Object

Use Object.values to get the values of the Object:

let values = Object.values(user);
values; // ["Balaji", 23, ƒ, 65]

Get the entries of the object

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, use Reflect.ownKeys(obj) to returns all keys; or, use Object.getOwnPropertySymbols to only get symbolic keys.

RELATED TAGS

javascript
objects
RELATED COURSES

View all Courses

Keep Exploring