JavaScript Object.keys, Values, Entries

JavaScript Object.keys, Values, Entries

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

JavaScript provides three powerful methods for working with objects:

  • Object.keys(obj) → Returns an array of keys
  • Object.values(obj) → Returns an array of values
  • Object.entries(obj) → Returns an array of key-value pairs

1. Object.keys(obj) – Get Keys

This method returns an array of all the keys (property names) of an object.

Example

const user = { name: "Alice", age: 25, country: "USA" }; console.log(Object.keys(user)); // Output: ["name", "age", "country"]

Use Case

You can use Object.keys() to loop through an object:

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

Output:

name: Alice age: 25 country: USA

2. Object.values(obj) – Get Values

This method returns an array of all the values in an object.

Example

console.log(Object.values(user)); // Output: ["Alice", 25, "USA"]

Use Case

Calculate the total sum of an object’s numeric values:

const salaries = { Alice: 5000, Bob: 7000, Charlie: 6000 }; const totalSalary = Object.values(salaries).reduce((sum, salary) => sum + salary, 0); console.log(totalSalary); // Output: 18000

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

This method returns an array of key-value pairs, where each item is a sub-array [key, value].

Example

console.log(Object.entries(user)); /* Output: [ ["name", "Alice"], ["age", 25], ["country", "USA"] ] */

Use Case

Loop through an object using forEach():

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

Convert an Object into a Map

const userMap = new Map(Object.entries(user)); console.log(userMap.get("name")); // Output: Alice

When to Use Each Method?

MethodReturnsUse Case
Object.keys(obj)Array of property namesLooping through keys, checking object properties
Object.values(obj)Array of property valuesSumming values, filtering data
Object.entries(obj)Array of [key, value] pairsConverting to Map, iterating with both keys and values

Summary

Object.keys() → Extracts keys from an object.
Object.values() → Extracts values from an object.
Object.entries() → Extracts key-value pairs from an object.

These methods are useful for iterating over objects, transforming data, and working with dynamic keys! Let me know if you need more examples. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close