🥮Objects Continued

In JavaScript, Object.keys(obj), Object.values(obj), and Object.entries(obj) are methods that can be used to access the keys, values, and key-value pairs of an object, respectively.

Object.keys(obj) returns an array of the object's own enumerable properties, 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).

let person = {
  name: "John",
  age: 30,
  job: "Developer"
};
console.log(Object.keys(person)); // Output: ["name", "age", "job"]

Object.values(obj) returns an array of the object's own enumerable property values, in the same order as that provided by a for...in loop.

let person = {
  name: "John",
  age: 30,
  job: "Developer"
};
console.log(Object.values(person)); // Output: ["John", 30, "Developer"]

Object.entries(obj) returns an array of the object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop.

let person = {
  name: "John",
  age: 30,
  job: "Developer"
};
console.log(Object.entries(person)); 
// Output: [ ["name","John"], ["age",30], ["job","Developer"] ]

Note that these methods are available only in modern browsers and if you are trying to run this on older browsers you have to use a polyfill or a library like lodash.

These methods are useful when you need to iterate over an object's properties or access its values in a specific order, for example, for displaying an object's data in a table. They also can be useful when you want to convert object to array for using array methods like filter, map, and reduce.

Last updated