Imo
Imo

Reputation: 1475

How to bind an json value that has space in its name with variable

I have a variable

var uniqueData = data[selectedIndex].values[0];

I want to bind it to differnt values from a json dataset to extract the value

when I do the follwoing it works fine

var elec_plants = uniqueData.Total;
console.log(elec_plants)

But there are some values with spaces inside such as

Main activity electricity and heat production: "1.4"

how can I bind it to uniqueData?

UniqueData.Main activity electricity and heat production

throws errors

Upvotes: 0

Views: 104

Answers (2)

Hristo Borisov
Hristo Borisov

Reputation: 86

Basically, in your case the value is not valid JavaScript identifier, so you have to use square brackets notation:

"An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)."

You can have a look at this article: Working with objects

Upvotes: 1

wizzardmr42
wizzardmr42

Reputation: 1644

uniqueData['Main activity electricity and heat production']

Upvotes: 1

Related Questions