JavaScript: How to get value by key

While working in javascript, often there is a requirement to get the value of an object for a particular key. This article will discuss accessing the value of a javascript object by key.

There are two easy ways to get the value corresponding to the key of an object

First using square brackets ‘[ ]‘ , example: object[“property_name”]

Second using dot operator ‘ . ‘, example: object.property_name

Example1:-

  • Get the value for key ‘personLastName’ in the object:
  • { personFirstName : ‘George’, personLastName : ‘Smith’, dateOfBirth : ‘Nov 14 1984’ }

Code:-

// object definition
let personObject =  { personFirstName : 'George',
                      personLastName  : 'Smith',
                      dateOfBirth     : 'Nov 14 1984' 
                    };
// usage of function findKey()
console.log(personObject["dateOfBirth"]);
console.log(personObject.personLastName);

Output:-

Nov 14 1984
Smith

Example2:-

  • Get the value for key ‘Veronica’ in the object:
  • { George : “Santiago”, Veronica : “Monroe”, Paul : “NewYork”, Mounika : “NewYork” }

Code:-

// object definition
let cityInfo = {
  George   : "Santiago",
   Veronica  : "Monroe",
   Paul : "NewYork",
   Mounika : "NewYork"
};
// usage of function findKey()
console.log(cityInfo["Veronica"]);
console.log(cityInfo.Mounika);

Output:-

Monroe
NewYork

I hope this article helped you to get the value by key in a javascript object. Good Luck !!!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top