Object.entries()
Object.entries() is a built-in JavaScript method
that returns an array of pairs [key, value] for all own (non-inherited) enumerable properties of an object.
Syntax
javascript
Object.entries(obj)obj- the object whose properties need to be converted into pairs.- Returns an array of arrays, where each inner array is
[key, value].
Example
javascript
const user = {
name: 'Tim',
age: 25,
city: 'Berlin'
};
console.log(Object.entries(user));Result:
javascript
[
['name', 'Tim'],
['age', 25],
['city', 'Berlin']
]Each [key, value] pair is an element of the resulting array.
Features
- Returns only own properties:
javascript
const base = { type: 'human' };
const user = Object.create(base);
user.name = 'Tim';
console.log(Object.entries(user)); // [['name', 'Tim']]- Returns only enumerable properties (
enumerable: true):
javascript
const obj = {};
Object.defineProperty(obj, 'hidden', { value: 42, enumerable: false });
obj.visible = 10;
console.log(Object.entries(obj)); // [['visible', 10]]- The order matches
Object.keys()andObject.values().
Often used to iterate over an object
javascript
const user = { name: 'Tim', age: 25 };
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}Will print:
javascript
name: Tim
age: 25Example: converting an object to a Map
javascript
const user = { name: 'Tim', age: 25 };
const userMap = new Map(Object.entries(user));
console.log(userMap.get('age')); // 25Object.entries() is convenient for converting between Object and Map.
Example of the reverse conversion (from pairs back to an object)
javascript
const entries = [
['name', 'Tim'],
['age', 25]
];
const user = Object.fromEntries(entries);
console.log(user); // { name: 'Tim', age: 25 }SUMMARY
| Method | What it returns | Considers the prototype | Data type |
|---|---|---|---|
Object.keys(obj) | array of keys | No | Array<string> |
Object.values(obj) | array of values | No | Array<any> |
Object.entries(obj) | array of [key, value] pairs | No | Array<[string, any]> |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.