-1

I have below json data in the variable .

var links = {
  info: {
   title: "Informatics "

  },
  busi: {
   title: "Business"

  },
  lang: {
   title: "Language"

  }
};

In the code i have the variable named type which could have string as info,busi,lang and that variable is getting as a function argument like

function get_data(type)
 {
    var data = JSON.parse(links);
    // Now i want to access the title of that particular type only I tried to use this but it didnt work 
    // data.type 
    // where as if i use the exact word it shows me data like this data.info 
  }

I want to make the code more generalize rather than sticking to constants like info, busi ,land . Any suggestions how can i make it more generalize ?

Uahmed
  • 1,847
  • 5
  • 29
  • 45

1 Answers1

3

To reference dynamic property names, rather than statically, you need square bracket, not dot, syntax.

data.type - looks for a property named 'type'

data[type] - looks for a property whose name is contained within a variable type

Mitya
  • 33,629
  • 9
  • 60
  • 107