2016-04-27 129 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