0 day streak
javascript / intermediate
Snippet

Transforming Pairs into Objects with fromEntries

Object.fromEntries transforms a list of key-value pairs into an object. It is the inverse of Object.entries and is extremely useful for transforming data or converting Map instances into plain objects.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const entries = [
['role', 'editor'],
['level', 5]
];
const userConfig = Object.fromEntries(entries);
console.log(userConfig.role);
const updated = Object.fromEntries(
Object.entries(userConfig).map(([k, v]) => [k, String(v).toUpperCase()])
);
Breakdown
1
Object.fromEntries(entries)
Converts an array of arrays into a standard JavaScript object.
2
Object.entries(userConfig)
Breaks the object back into an iterable array of [key, value] pairs.
3
.map(([k, v]) => [k, ...])
Allows for easy manipulation of both keys and values during the transformation process.