JavaScript Object Get Value By Key

JavaScript Object Get Value By Key | The name of the property serves as the object’s key. The key can be compared to an associative array’s named index. An associative array is not available in JavaScript. Instead, key-value pairs are stored as JavaScript objects. Also see:- JavaScript Find Object In Array By Property Value

In most cases, the object’s key is known, and with the help of the key, you can access the value of the object. There are two ways to get to the object’s value:-

  • Dot Notation
  • Square Brackets

JavaScript Object Get Value By Key Using Dot Notation

The most popular method for gaining access to an object’s value is the dot notation. To use it, write the name of the object, a dot, and the name of the key in that order. Case in point: Name (where the person is an object and name is the key).

var person = {
  name: "John",
  age: 30,
  city: "New York",
};

console.log(person.name);
console.log(person.age);
console.log(person.city);

Output:-

John
30
New York

JavaScript Object Get Value By Key Using Brackets

Another approach to retrieve the object’s value is via the square bracket. Write the name of the object, a square bracket, the name of the key, and then utilize this. Person[“name”] example (where the person is an object and name is the key).

var person = {
  name: "John",
  age: 30,
  city: "New York",
};

console.log(person["name"]);
console.log(person["age"]);
console.log(person["city"]);

Output:-

John
30
New York

JavaScript Object Gets Value From Key Variable

When an object’s key is saved in a variable, there are instances when you need to retrieve the key’s value. This situation occurs frequently. You get undefined while attempting to get the value right now using the variable. Here is an illustration of this.

const person = {
  name: "John",
  age: 30,
  city: "New York",
};

var userName = "name";
console.log(person.userName);

Output:-

undefined

Because Javascript sees “userName” as a key rather than a variable, the code above will print undefined in the console. Undefined will be returned since the variable is not a key of the object. Therefore, use the square bracket syntax to retrieve the value of the object when the key is stored in a variable.

const person = {
  name: "John",
  age: 30,
  city: "New York",
};

var userName = "name";
console.log(person[userName]);

Output:-

John

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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