1

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

It works fine, returning gerar-evento, but if I try:

dataLayer[3].event-label

I get this error: ReferenceError: label is not defined

Is there another way to select a property from an object? What am I doing wrong?

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
user3347814
  • 1,138
  • 9
  • 28
  • 50

2 Answers2

5

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

dataLayer[3]['event-label']
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 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
3

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
  • 6,015
  • 6
  • 36
  • 46