How To Get An Object’s Value By Variable Key In JavaScript

Get an Object's Value by Variable Key in JavaScript

If you want to get an object’s value by variable key in JavaScript, follow me till the end of this article. I’ll make it simple through the syntax where we can directly access the Object’s properties. Like using a dot to call or using the [] syntax. Here are some examples to help us understand more about these two methods.

Get an Object’s Value by Variable Key in JavaScript

To get an object’s value by variable key, we will use the syntax to access the Object’s properties from which we can get its values.

Accessing properties from objects with a dot

With this method, we can get the object’s value by directly calling a property we want to get its value.

Syntax:

objectName.property

Example:

var Animal = {
	'name': 'Dog',
	'legs': 4,
	'isTail': true
};

// Get a value of Object by Variable Key using dot syntax
console.log('Name: ' + Animal.name);
console.log('Legs: ' + Animal.legs);
console.log('IsTail: ' + Animal.isTail);

Output:

Name: Dog
Legs: 4
IsTail: true

In this case, we can get any value of any property of the object we want, but in below, we cannot access a property whose name appears with special characters.

Example:

var Animal = {
	'name': 'Dog',
	'legs': 4,
	'is-Tail': true
};

// Get a value of Object by Variable Key using dot syntax
console.log('Name: ' + Animal.name);
console.log('Legs: ' + Animal.legs);
console.log('IsTail: ' + Animal.is - Tail);

Output:

Name: Dog
Legs: 4
Uncaught ReferenceError: Tail is not defined

Accessing properties from objects using square brackets

This way, we can overcome the error of using dot syntax to get the object’s value by variable Key.

Syntax:

objectName['property']

or

objectName[expression]

Example:

var Animal = {
	'name': 'Dog',
	'legs': 4,
	'is-Tail': true
};

// Get a value of Object by Variable Key using [] syntax
console.log('Name: ' + Animal['name']);
console.log('Legs: ' + Animal['legs']);
console.log('IsTail: ' + Animal['is-Tail']);

Output:

Name: Dog
Legs: 4
IsTail: true

In this example, we see that this method can be used to access a property that appears with memorable characters. Not only can it also access the object’s properties, but it also uses dot syntax.

We can use the [] syntax as follows:

var Animal = {
	'is*Tail': true
};

var property = 'is*Tail';

// Get a value of Object by Variable Key using [] syntax
console.log('IsTail: ' + Animal[property]);

Output:

IsTail: true

Summary

In the above article, I have introduced two ways to get an object’s value by variable key in JavaScript. I always prefer accessing properties from objects with a dot but for cases where there are special characters in the Object’s property name. I hope this article helps you and your program. Good luck.

Maybe you are interested:

Leave a Reply

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