Object.values() Method

This week I'm tackling Object.values(), which is fairly straightforward. When you run Object.values() against a data object, the method returns an array of the object's property values.

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

const attributes = Object.values(person);
console.log(attributes);
// expected output:
// ["Joey", 31, "Web Developer", "Austin, Texas", true]

The Object.values() method gives us a way to unpack the contents of a box in an orderly fashion.

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

const attributesArray = [];

for (const attribute in person) {
  attributesArray.push(person[attribute]);
};
console.log(attributesArray);
// expected output:
// ["Joey", 31, "Web Developer", "Austin, Texas", true]

One little gotcha to be aware of is that if the keys are numeric, Object.values() will output the items in the numeric order of the keys.

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

const objValues = Object.values(obj);
console.log(objValues);
// expected output:
// ["Puffin", "Armadillo", "Giraffe", "Lion", "Octopus"]

Lastly, if you run Object.values() against a simple array, all you get is a copy of the array:

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

const objValues = Object.values(colors);
console.log(objValues);
// expected output:
// ["red", "orange", "yellow", "green", "blue", "violet"]

From MDN: The Object.values() method returns an array of a given object's own enumerable property values, 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.