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:

```js 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 πŸ¦„

```js 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:

js 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. ✌️