JavaScriptObjects and classes
Object. entries()
Returns an array of an object’s [key, value] pairs.
- Returns
- An array of
[key, value]pairs. - Changes the original
- No
Example
#JavaScript
const prices = { html: 49, css: 59 }
for (const [course, price] of Object.entries(prices)) {
console.log(`${course}: $${price}`)
}
console.log(Object.entries(prices))Console
html: $49
css: $59
[['html', 49], ['css', 59]]
Definition and usage
#The Object.entries() method turns an object into an array of two-element arrays: [key, value]. That lets you walk over an object with a for...of loop and destructuring, or transform it with array methods.
Paired with Object.fromEntries(), it forms a popular pattern: turn an object into pairs, filter or map them, then assemble it back into an object.
The result can also be passed straight to the Map constructor, which accepts exactly this kind of list of pairs.
Syntax
#Syntax
Object.entries(obj)Parameters
#obj
object
The object to turn into pairs.
More examples
#JavaScript
const scores = { emma: 92, jack: 58, mia: 77 }
const passed = Object.fromEntries(
Object.entries(scores).filter(([, score]) => score >= 60)
)
console.log(passed)Console
{ emma: 92, mia: 77 }
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- The pattern
Object.fromEntries(Object.entries(obj).filter(...))is a readable way to filter an object. - An empty slot in the destructuring,
[, score], skips the key when you only need the value.
Related entries
#- Object.fromEntries()Creates an object from a list of [key, value] pairs.
- Object.keys()Returns an array of an object’s own, enumerable property names.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
Spotted a mistake or missing an example? Write to us.