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:
- Validation: Checking the number of properties in an
object using
Object.keys(obj).length. - Dynamic Property Access: Iterating through keys to inspect or modify corresponding values dynamically.
- Key Verification: Checking if specific keys exist within a dynamic dataset.
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:
- Calculations: Performing mathematical operations,
such as summing numerical values using
.reduce(). - Value Searching: Checking if a specific value
exists in an object using array methods like
.includes(). - Data Extraction: Flattening an object when the property names are irrelevant to the operation.
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:
Looping with Destructuring: Cleanly iterating through both keys and values using a
for...ofloop:for (const [key, value] of Object.entries(settings)) { console.log(`${key}: ${value}`); }Object Transformation: Filtering or modifying an object’s keys and values simultaneously in combination with
Object.fromEntries().Map Conversion: Creating a new
Mapinstance directly from an existing object (new Map(Object.entries(obj))).
Summary
- Use
Object.keys()when you only need property names. - Use
Object.values()when you only need the data values. - Use
Object.entries()when you need both keys and values together.