Object.fromEntries (ES2019) - An elegant inverse of Object.entries (ES2017)
Shahzaib Khalid
Posted on August 28, 2019
Hey! π
Check out today's Dev Tip! π
Follow me on Twitter @shahzaibkhalid for more Dev Tips! β¨
Object.entries π
For each key-value pair in an object, Object.entries
gives you an array where the first element is the key, and the second element is the value.
Object.entries
is especially useful in combination with for-of, as it enables you to very elegantly iterate over all key-value pairs in an object:
const object = { x: 42, y: 50 };
const entries = Object.entries(object);
// β [['x', 42], ['y', 50]]
for (const [key, value] of entries) {
console.log(`The value of ${key} is ${value}.`);
}
// Logs:
// The value of x is 42.
// The value of y is 50.
Unfortunately, thereβs no easy way to go from the entries result back to an equivalent objectβ¦ until now! π
Object.fromEntries π¦
const object = { x: 42, y: 50 };
const entries = Object.entries(object);
// β [['x', 42], ['y', 50]]
const result = Object.fromEntries(entries);
// β { x: 42, y: 50 }
Practical Usage π
One common use case is transforming objects. You can now do this by iterating over its entries, and then using array methods you might already be familiar with:
const object = { x: 42, y: 50, abc: 9001 };
const result = Object.fromEntries(
Object.entries(object)
.filter(([ key, value ]) => key.length === 1)
.map(([ key, value ]) => [ key, value * 2 ])
);
// β { x: 84, y: 100 }
Hope you learned something new today. Do let me know what do you think about this Dev Tip in the comments below. π
Peace. βοΈ
Posted on August 28, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.