Object.keys, Object.values, and Object.entries in JS

JavaScript provides three essential static methods—Object.keys(), Object.values(), and Object.entries()—to extract data from objects into standard JavaScript arrays. These methods simplify the process of looping over objects, transforming data, and leveraging powerful array methods like .map(), .filter(), and .reduce() on key-value collections. This article explains the specific purpose, behavior, and practical use cases for each method.

Object.keys()

Object.keys() takes an object as an argument and returns an array containing all of that object’s own enumerable property names (keys), formatted as strings.

const user = { name: "Alex", role: "Developer", active: true };
console.log(Object.keys(user));
// Output: ["name", "role", "active"]

Primary Uses:

Object.values()

Object.values() takes an object as an argument and returns an array containing all of the object’s own enumerable property values.

const inventory = { apples: 10, oranges: 5, bananas: 12 };
console.log(Object.values(inventory));
// Output: [10, 5, 12]

Primary Uses:

Object.entries()

Object.entries() takes an object as an argument and returns an array of the object’s own enumerable string-keyed property [key, value] pairs. Each entry is a two-element array where the first item is the key and the second is the value.

const settings = { theme: "dark", notifications: true };
console.log(Object.entries(settings));
// Output: [["theme", "dark"], ["notifications", true]]

Primary Uses:

Summary