Learnitweb

What is the difference between Object.entries, Object.keys and Object.values methods?

This is a popular JavaScript interview question to test knowledge about the Object methods. We’ll discuss all these three methods with an example.

1. Object.entries()

The Object.entries() method returns an array of given object’s own enumberable [key, value] pairs. The order of the array returned by Object.entries() is same as that provided by a for…in loop.

const employee = {
  id: 1,
  name: "James",
};

console.log(Object.entries(employee)); // [ [ 'id', 1 ], [ 'name', 'James' ] ]

2. Object.keys()

The Object.keys() method returns an array of a given object’s own enumerable property names. The elements of the array are strings corresponding to the enumerable properties of the objects.

const employee = {
  id: 1,
  name: "James",
};

console.log(Object.keys(employee)); // [ 'id', 'name' ]

3. Object.values()

The Object.values() method returns an array of a given object’s own enumerable property values. The order of array returned by Object.values() is same as that provided by a for…in loop.

const employee = {
  id: 1,
  name: "James",
};

console.log(Object.values(employee)); // [ 1, 'James' ]