2016-04-27 127 views
-1

我有以下JSON数据的变量。Json数据访问

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

    }, 
    busi: { 
    title: "Business" 

    }, 
    lang: { 
    title: "Language" 

    } 
}; 

在代码中,我有自己的变量命名的类型可能有串的信息,布丝,郎变量越来越像

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 
    } 

我想使代码更函数参数概括而不是坚持像信息,商业,土地等常数。任何建议如何使它更一般化?

+0

请注意,您的问题无关,与JSON的属性。 JavaScript与JSON不同。 –

+0

相关:[访问/进程(嵌套)对象,数组或JSON](http://stackoverflow.com/q/11922383/218196) –

回答

3

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

data.type - 查找名为“类型”

data[type]属性 - 查找其名称中包含一个变量type

+1

谢谢,它的工作! – Uahmed

+0

太好了。在这种情况下,请接受答案。 – Utkanos