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

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

Let?s dive into objects

Image for postPhoto 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); //output0: (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]}`);}//outputuser[name] = Johnuser[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:

  • MDN Web Docs
  • JavaScript.info

Follow Javascript Jeep??

Sign In | Sitepoint

Unsupported Browser Although our tracking technology supports older browsers, unfortunately our website does not?

sitepoint.tapfiliate.com

12

No Responses

Write a response