1

I have a value in this format:

var state = [{"industry-type":"football","your-role":"coach"}]

I would like to output "football". How can I do this?

I've tried state[0].industry-type but it returns an error:

Uncaught ReferenceError: type is not defined

Any help appreciated.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
londonfed
  • 1,170
  • 2
  • 12
  • 27

5 Answers5

2

It does not like the '-' in your property name, try:

state[0]['industry-type']
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
paul
  • 21,653
  • 1
  • 53
  • 54
1

This happens because you can't access a property with - directly.

var state = [{"industry-type":"football","your-role":"coach"}];

console.log(state[0]['industry-type']);
Erazihel
  • 7,295
  • 6
  • 30
  • 53
1

The - symbol is reserved in Javascript, you cannot use it to refer to an object's property because Javascript thinks you're trying to do subtraction: state[0].industry - type; Hence the error "Uncaught ReferenceError: type is not defined" - it is looking for a variable named type to subtract with, which it can't find.

Instead, refer to it by:

state[0]['industry-type']

Because in Javascript, object.property and object['property'] are equal.


For what it's worth, if you have control over those names, it is best practice in Javascript to name things with Camel Case, so your variable would be defined as:

var state = [{"industryType":"football","yourRole":"coach"}]

Then, you could access it like:

state[0].industryType
qJake
  • 16,821
  • 17
  • 83
  • 135
1

In order to be able to use dot notation then your:

...property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.

From MDN

Like the other answers pointed out, you have to use square bracket notation to access property names of an object that are not valid JavaScript identifiers.

e.g.

state[0]["industry-type"]

Related SO question:

What characters are valid for JavaScript variable names?

Community
  • 1
  • 1
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

You'll need to use bracket notation for the attribute -

state[0]['industry-type']

skwidbreth
  • 7,888
  • 11
  • 58
  • 105