Object.entries() returns an array of key-value pairs from an object. Each pair is an array of two elements: the first element is the key, the second is the value. Convenient for converting object to Map or for iterating with destructuring.
const user = { name: 'John', age: 25 };
const entries = Object.entries(user);
console.log(entries); // [['name', 'John'], ['age', 25]]Object.entries() is a method that turns an object into an array of key-value pairs. This is very convenient when you need to work with an object as a set of pairs.
Returns array of arrays, where each inner array contains key and value:
const user = { name: 'John', age: 25 };
const entries = Object.entries(user);
console.log(entries); // [['name', 'John'], ['age', 25]]const obj = { name: 'John', age: 25 };
const map = new Map(Object.entries(obj));
// Now can use Map methodsconst user = { name: 'John', age: 25 };
for (let [key, value] of Object.entries(user)) {
console.log(key, value); // name John, age 25
}const config = {
theme: 'dark',
lang: 'en',
notifications: true
};
const configMap = new Map(Object.entries(config));
console.log(configMap.get('theme')); // 'dark'const users = {
'1': 'John',
'2': 'Peter',
'3': 'Mary'
};
// Find key by value
const entries = Object.entries(users);
const found = entries.find(([key, value]) => value === 'Peter');
console.log(found[0]); // '2'const obj = { name: 'John' };
// Doesn't include inherited methods like toString
console.log(Object.entries(obj)); // [['name', 'John']]const obj = { 3: 'three', 1: 'one', 2: 'two', a: 'letter' };
console.log(Object.entries(obj));
// [['1', 'one'], ['2', 'two'], ['3', 'three'], ['a', 'letter']]// Convenient to create Map from object
const obj = { a: 1, b: 2 };
const map = new Map(Object.entries(obj));const obj = { a: 1, b: 2, c: 3 };
// Keep only values greater than 1
const filtered = Object.fromEntries(
Object.entries(obj).filter(([key, value]) => value > 1)
);
console.log(filtered); // { b: 2, c: 3 }// ❌ Thinking we get object
const obj = { a: 1, b: 2 };
const result = Object.entries(obj);
console.log(result); // Array of arrays, not object!
// ✅ Proper understanding
console.log(Array.isArray(result)); // true
console.log(Array.isArray(result[0])); // true// ❌ Trying to use with primitives
Object.entries(42); // Error!
// ✅ Only with objects
Object.entries({ value: 42 }); // [['value', 42]]Object.entries() is useful when you need to work with an object as a set of pairs. Especially convenient when converting to Map or when iterating with destructuring.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪