Object.keys, values, entries in Javascript

Object.keys, values, entries in Javascript

For plain objects, the following methods are available:

  • Object.keys(obj) – returns an array of keys.
  • Object.values(obj) – returns an array of values.
  • Object.entries(obj) – returns an array of [key, value] pairs.

Please note that we have to call Object.keys(obj), and not obj.keys().

Why so? The main reason is flexibility. Remember, objects are a base of all complex structures in JavaScript. So we may have an object of our own like data that implements its own data.values() method. And we still can call Object.values(data) on it.

The second difference is that Object.* methods return “real” array objects, not just an iterable. That’s mainly for historical reasons.

For instance:

let user = {
  name: "John",
  age: 30
};

Object.keys(user) = ["name", "age"]
Object.values(user) = ["John", 30]
Object.entries(user) = [ ["name","John"], ["age",30] ]

Here’s an example of using Object.values to loop over property values:

let user = {
  name: "John",
  age: 30
};

// loop over values
for (let value of Object.values(user)) {
  alert(value); // John, then 30
}

Iterating through that array

For instance, from an object of employees, we can sum up their salaries by iterating through the values of each item from the object. For simplicity, we can use the Object.values() method in a for... of loop:

let salaries = {
  "John": 100,
  "Pete": 300,
  "Mary": 250
};

function sumSalaries(salaries) {
  let sum = 0;
  for (let salary of Object.values(salaries)) {
    sum += salary;
  }

  return sum;
}

alert( sumSalaries(salaries) ); // 650