Object.fromEntries (ES2019) - An elegant inverse of Object.entries (ES2017)

shahzaibkhalid

Shahzaib Khalid

Posted on August 28, 2019

Object.fromEntries (ES2019) - An elegant inverse of Object.entries (ES2017)

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.
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

Hope you learned something new today. Do let me know what do you think about this Dev Tip in the comments below. πŸ‘€

Peace. ✌️

πŸ’– πŸ’ͺ πŸ™… 🚩
shahzaibkhalid
Shahzaib Khalid

Posted on August 28, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related