JavaScript Object.keys(), Object.values(), Object.entries()


These ES6 object methods allow you to work with objects more effectively by converting object data into arrays. This is especially useful for loops, transforms, and data manipulation.



1. Object.keys() – Get Property Names


The Object.keys() method returns an array of an object's own property names (keys).

Example:

const user = {
  name: "Alice",
  age: 25,
  city: "New York"
};

const keys = Object.keys(user);
console.log(keys);

Output

["name", "age", "city"]

Use When: You need to loop over or count the keys of an object.



2. Object.values() – Get Property Values


The Object.values() method returns an array of the object's values.

Example:

const values = Object.values (user);
console.log(values);

Output

["Alice", 25, "New York"]

Use When: You only care about the data, not the property names.



3. Object.entries() – Get Key-Value Pairs


The Object.entries() method returns an array of the object's key-value pairs as nested arrays.

Example:

const entries = Object.entries(user);
console.log(entries);

Output

[
["name", "Alice"],
["age", 25],
["city", "New York"]
]

Use When: You want to loop over both keys and values at the same time.



4. Looping with forEach()


Example using Object.entries():

Object.entries(user).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

Output

name: Alice
age: 25
city: New York


5. Convert entries Back to Object


You can convert entries back into an object using Object.fromEntries().

Example:

const entriesBack = Object.fromEntries(entries);
console.log(entriesBack);

Output

{ name: "Alice", age: 25, city: "New York" }


Real-World Use Cases

  • Count object properties: Object.keys(obj).length
  • Convert object data to arrays for processing or UI rendering
  • Loop through objects like arrays
  • Transform object into another format (e.g., table, dropdowns)