0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Object.entries in JavaScript: Syntax and Examples

Use Object.entries(object) to get an array of [key, value] pairs from an object. This helps you loop over or manipulate object properties easily as arrays.
📐

Syntax

The Object.entries() method takes an object as input and returns an array of arrays, where each inner array contains two elements: the key and the value from the object.

  • object: The object you want to convert.
  • Returns: An array of [key, value] pairs.
javascript
Object.entries(object)
💻

Example

This example shows how to use Object.entries() to get key-value pairs from an object and loop through them with for...of.

javascript
const user = { name: 'Alice', age: 25, city: 'Paris' };

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

for (const [key, value] of entries) {
  console.log(`${key}: ${value}`);
}
Output
[['name', 'Alice'], ['age', 25], ['city', 'Paris']] name: Alice age: 25 city: Paris
⚠️

Common Pitfalls

One common mistake is trying to use Object.entries() on null or undefined, which causes an error. Also, it only works on own enumerable properties, so inherited properties are not included.

Wrong usage example:

javascript
const obj = null;

// This will throw an error
Object.entries(obj);
📊

Quick Reference

MethodDescription
Object.entries(obj)Returns array of [key, value] pairs from obj
Object.keys(obj)Returns array of keys from obj
Object.values(obj)Returns array of values from obj

Key Takeaways

Object.entries() converts an object into an array of [key, value] pairs.
Use it to loop over object properties easily with array methods or loops.
It only works on own enumerable properties, not inherited ones.
Passing null or undefined to Object.entries() causes an error.
It pairs well with destructuring to access keys and values clearly.