0

This is a very strange error, I can´t figure out why it´s happening.

I have a dataLayer array that has objects inside it.

dataLayer[3]
Object {event: "gerar-evento", event-category: "Chat", event-acion: "Vendas", event-label: "Pré Fixo 15"}

When I try to select a property of this object I get an error

if I try:

dataLayer[3].event //gerar-evento

it works fine.

But if I try:

dataLayer[3].event-label // ReferenceError: label is not defined

I get this error: ReferenceError: label is not defined

Is there a another way to select a property from a object? What I´m doing wrong?

user3347814
  • 895
  • 9
  • 22
  • 42

2 Answers2

4

You need to use bracket notation since event-label is not a valid identifier

dataLayer[3]['event-label']
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520
  • 2
    In case it's not clear why `event-label` isn't a valid identifier: it's an expression that subtracts a variable called `label` from one called `event`. – Wyzard Aug 30 '14 at 03:36
2

In JavaScript you have two ways to get object properties:

  1. Dot notation: object.property

  2. Bracket notation: object['property-with-dash'] which is the one you have to use in your case:

    dataLayer[3]['event-category']

Also with the bracket notation, you can use variables to get properties out of the object, for example:

 var eventName = 'event-category';
 dataLayer[3][eventName]

would give you the same result.

Mimo
  • 5,885
  • 6
  • 34
  • 45