Json Data Acess

时间:2016-04-27 11:54:19

标签: javascript json

我在变量中有json数据。

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

  },
  busi: {
   title: "Business"

  },
  lang: {
   title: "Language"

  }
};

在代码中我有一个名为type的变量,它可以将字符串作为info,busi,lang和该变量作为函数参数获取,如

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 
  }

我想让代码更加通用,而不是坚持像info,busi,land这样的常量。任何建议我怎样才能使它更通用化?

1 个答案:

答案 0 :(得分:3)

要引用动态属性名称,而不是静态引用,则需要使用方括号,而不是点,语法。

data.type - 查找名为' type'

的媒体资源

data[type] - 查找名称包含在变量type

中的属性
相关问题