Access An Object Property With A Hyphen In JavaScript

Access an Object Property with a Hyphen in JavaScript

The way to Access an object property with a hyphen in JavaScript is relatively easy. In this article, I will help you understand and implement it through some specific examples. Let’s learn it below.

How to access an object property with a hyphen in JavaScript?

To access the property of an object, we will access the property we want to call directly from the object through dots or brackets.

Property access from an object with a dot

You can access an object’s properties using a dot. Most setup members will use this to call the object’s properties. Look at the following syntax:

Syntax:

objectName.property

Example:

var product = {
    "name": "product1",
    "price": 1000,
    "quantity": 10
}

// Access properties with dot syntax
console.log("Product Name: " + product.name);
console.log("Price: " + product.price);
console.log("Quantity: " + product.quantity);

Output:

Product Name: product1
Price: 1000
Quantity: 10

From the above example, this method is relatively quick and simple to access an object’s property. Still, for this method, if we call a property that has a character trait, it will return an error or undefined value. So we cannot use it to access hyphenated object properties.

Accessing properties with square brackets

This method will access properties from an object with a dot because it is possible to access properties whose keys have a character trait present.

Syntax:

objectName["property"]

Or

objectName [expression]

Example:

var product = {
    "product-name": "product1",
    "product_price": 1000,
    "product quantity": 10
}

// Access properties with [] syntax
console.log("Product Name:" + product["product-name"]);
console.log("Price:" + product ["product_price"]);
console.log("Quantity: " + product["product quantity"]);

Output:

Product Name: product1
Price: 1000
Quantity: 10

In the above example, I used spaces, asterisks, and dashes to name the object’s key with the dot. We can’t call it, but for the [] syntax, we can call key strings with special characters.

We can access properties with [] syntax differently as follows:

var product = {
    "product-name": "product1",
    "product * price": 1000,
    "products quantity": 10
}

var quantity = "products quantity";

// Access properties with [] syntax
console.log("Quantity: " + product [quantity]);

Output:

Quantity: 10

You can save the property’s name in another variable and then use that variable inserted between brackets instead, and the result will not be changed.

Summary 

In this article, I showed you how to access an object property with a hyphen in JavaScript using [] syntax to access the object’s properties. This will help you remember it longer. 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 *