Object.entries() Method

Object.entries() also goes hand in hand with the Object.keys() and Object.values() methods. However, where each of those methods returned an array of keys or values respectively, for each [key, value] pair in an object, Object.entries() will return an array of...well, [key, value]. Let's check it out. Once again I'll be using the same examples from Object.keys() and Object.values().

const person = {
  name: "Joey",
  age: 31,
  occupation: "Web Developer",
  location: "Austin, Texas",
  hungry: true,
};

const objEntries = Object.entries(person);
console.log(objEntries);
// expected output:
// [["name", "Joey"], ["age", 31], ["occupation", "Web Developer"], ["location", "Austin, Texas"], ["hungry", true]]

If Object.values() is the contents of the box, and Object.keys() is the tape that holds the box together, then Object.entries() is the whole box. It gives us a way to iterate over the entire data object, including both keys and values. And it does so in a way that some might find easier to read than a for...in loop.

The above code produces the same result as this for...in loop:

let loopedEntries = [];
for (entry in person) {
  loopedEntries.push([entry, person[entry]]);
};
console.log(loopedEntries);
// expected output:
// [["name", "Joey"], ["age", 31], ["occupation", "Web Developer"], ["location", "Austin, Texas"], ["hungry", true]]

As with Object.keys() and Object.values(), one should be on the lookout for numeric keys and the order in which they are output:

const obj = {
  5: "Giraffe",
  70: "Octopus",
  17: "Lion",
  1: "Armadillo",
  0: "Puffin",
};

const objEntries = Object.entries(obj);
console.log(objEntries);
// expected output:
// [["0", "Puffin"], ["1", "Armadillo"], ["5", "Giraffe"], ["17", "Lion"], ["70", "Octopus"]]

And lastly, if you run Object.entries() against a simple array, you get arrays with both the indices and the values:

const colors = ["red", "orange", "yellow", "green", "blue", "violet"];

const objEntries = Object.entries(colors);
console.log(objEntries);
// expected output:
// [["0", "red"], ["1", "orange"], ["2", "yellow"], ["3", "green"], ["4", "blue"], ["5", "violet"]]

From MDN: The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for...in loop enumerates properties in the prototype chain as well).

See more examples and documentation here.