DEV Community

Neha Sharma
Neha Sharma

Posted on

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!!

Top comments (0)