Iterate over properties
Need to process both names and values in an object.
JavaScript · Function
Object.entries() returns an array of [key, value] pairs for an object's own enumerable string-keyed properties. It excludes inherited properties and preserves the standard property-enumeration order.
Call Object.entries with an object-like value to receive an array of two-item arrays. Each inner array contains an own enumerable string property key followed by its value; inherited properties are excluded, and the entries follow the object's property enumeration order.
Object.entries(obj)| Name | Type | Description |
|---|---|---|
obj | object | The value converted to an object and inspected for own enumerable string-keyed properties. |
An array of the object's own enumerable string-keyed property key-value pairs; each pair is a two-element array containing a string key and its value.
const user = { name: "Ada", age: 36 };
for (const [key, value] of Object.entries(user)) {
console.log(`${key}: ${value}`);
}Iterates through each own enumerable string-keyed property as a two-item array.
Need to process both names and values in an object.
Need an iterable sequence of pairs for a collection constructor.
Need to transform or filter properties before rebuilding an object.
Object.entries(obj) returns an array of [key, value] pairs for the object's own enumerable string-keyed properties. Each key is a string, and inherited properties are not included.
Follow-up: How does it differ from for...in? Object.entries excludes prototype-chain properties, while for...in includes enumerable inherited properties.
The result is ordered like a for...in enumeration of the object's properties. The returned outer array contains one two-element array per matching property.
Follow-up: How would you get only one side of each pair? Use Object.keys for keys or Object.values for values.
It can be used with the Map constructor because the result is an iterable list of key-value pairs. For example, new Map(Object.entries(obj)) converts an object into a Map.
Follow-up: What is the reverse operation? Object.fromEntries converts a list of key-value pairs into an object, though it can also create symbol-keyed properties.
Object.keys()Object.values()Object.fromEntries()Map()