Accessing an Object’s Keys, Values, and Entries in JavaScript

Let’s dive into objects

Photo by Matt Artz on Unsplash
  • Object.keys(obj) → returns an array of a given object’s property names.
  • Object.values(obj) → returns an array of a given object’s own property values.
  • Object.entries(obj) → returns an array of a given object’s own string-keyed property [key, value] pairs.
var user = {
    name : "John",
    profession : "👨‍⚕️",
    salary  : 10000
}
Object.keys(user); // ["name", "profession", "salary"]
Object.values(user); // ["John", "👨‍⚕️", 10000]
Object.entries(user); 
//output
0: (2) ["name", "John"]
1: (2) [“profession”, “👨‍⚕️”]
2: (2) [“salary”, “10000]
length: 3

All the above three methods return only the enumerable property of the object.

var user = {
name : "John"
}
Object.defineProperty( user , 'salary', {
value: 10000,
enumerable: false
});

In the above code, we define a property salary and set enumerable property as false.This will make the salary hidden from the Object.keys.

Object.keys(user); ["name"]
Object.values(user); ["John"]
Object.entries(user); //  ["name", "John"]

We cannot loop through the symbol properties of the object.

var user = {
name : "John"
}

let Passcode = Symbol("Passcode");
user[Passcode] = "1234";

Now we have set the symbol as a property of the object, but this will not be accessible using the three methods above.

Object.keys(user); //["name"]
Object.values(user); // ["John"]
Object.entries(user); //  ["name", "John"]

To access the symbol property of the object, we can use getOwnPropertySymbols().

Object.getOwnPropertySymbols(user); //[Symbol(Passcode)]

We can use for… as an alternative to the above methods.

var user = {
name : "John",
age : 25
}
for(const property in user) {
console.log(`user[${property}] = ${user[property]}`);
}
//output
user[name] = John
user[age] = 25

Using map with Object.entries.

var user = {
name : "John",
age : 25
}
let entries = Object.entries(user);
entries.map( ([prop, val]) => console.log(prop, val));

Alternatively, we can also use forEach.

var user = {
name : "John",
age : 25
}
let entries = Object.entries(user);
entries.forEach( ([prop, val]) => console.log(prop, val));

Using for…of with Object.entries:

var user = {
name : "John",
age : 25
}
let entries = Object.entries(user);
for(const [prop, val] of entries) {
console.log(prop, val);
}

References:

Follow Javascript Jeep🚙💨

https://sitepoint.tapfiliate.com/p/payout-methods/new/

Leave a comment

Design a site like this with WordPress.com
Get started