1

I'll try and makes this succinct. My JSON data reads:

  "brand":{

   "active" : "brand1",

   "brand1" : {
    "bodyColour" : "#f2f2f2",
    "logoClickthroughURL" : "#"
   },

   "brand2" : {
    "bodyColour" : "#f2f2f2",
    "logoClickthroughURL" : "#"
   }

  }

I want to access the brand bodyColour and logoClickthroughURL based on what is active.

I've tried this:

var activeBrand = brand.active;
var activeBodyColour = brand.activeBrand.bodyColour;

This fires an error. I've tried to concat with "+" but no luck.

Any help is much appreciated.

Thanks, All.

Moe

Moe-Joe
  • 1,012
  • 3
  • 15
  • 27

1 Answers1

3

Use square brackets:

var activeBodyColour = brand[activeBrand].bodyColour

The reason dot notation doesn't work is it is looking for a key that is literally called 'activeBrand'. Bracket notation allows you to access a property using a variable key name.

Jordan Burnett
  • 1,799
  • 8
  • 11