DEV Community

Neha Sharma
Neha Sharma

Posted on

9 1

JavaScript Object: entries() vs fromEntries()

Do you know what is Object.entries() and fromEntries()?

Do you know what is the difference between the both?

No?? then keep reading.

Follow me on Twitter

Object.entries()

Convert a given object to an array of the enumerable own property.

It is different from 'for..in'. It iterates its own properties only. Whereas 'for..in' iterates properties in the prototype also.

Use it when you want to convert an object to array.

// Object.entries()

const fruits = { 
    'apple' : 3,
    'orange' : 4
}

const summerFruits = Object.create(fruits);

summerFruits.apple = 10;
summerFruits.kiwi = 5;

const summerFruitsList = Object.entries(summerFruits); // [['apple', 10], ['kiwi', 5]]
Enter fullscreen mode Exit fullscreen mode

Object.fromEntries()

Transforms a list of given key/value to an object.

Use it when you want to convert a list to an object.

Careful:

  • Keys should be different otherwise it will cascade it.

  • Strictly follow key-value pair.

// Object.fromEntries()

const fruits = [ [ 'apple' , 3] , ['orange', 4] ]

const summerFruitsList = Object.fromEntries(fruits); // {apple: 3, orange: 4}
Enter fullscreen mode Exit fullscreen mode

Happy learning!!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free