2012-01-20 276 views
1

所以我有一個基本組織這樣一個JSON對象(語法可能是錯的,但我認爲它橫跨得到的總體思路):訪問成員

var result = {{Name: 'name1', Type: 'type1', UserInfo: [{date:'123', location: 'earth'}]}, 
     {Name: 'name2', Type: 'type2', UserInfo: [{date:'456', location: 'mars'}]}}; 

我想訪問jQuery模板中的UserInfo數組內部的成員,但是我嘗試的所有內容都會導致我嘗試訪問的成員找不到或未定義的錯誤。

例如:

${UserInfo.date} 

${$UserInfo.date} 

${$item.UserInfo.date} 

誰能告訴我如何訪問這些陣列成員?

回答

0

所以你不需要jQuery來處理JSON。 JSON與JavaScript(JavaScript Object Notation)相關聯。

要訪問JSON對象,試試這個:

var innerArray = result[0].UserInfo; 

這將讓來自第一個目標的結果用戶信息陣列

+0

是的,如果我只是想訪問數據,我不需要jQuery,但我想要結果數組綁定到jQuery模板進行顯示。這是我遇到的問題。我想有一個更清晰的描述是必要的。 Template: $ {Name} < - This works $ {UserInfo} < - returns [object Object] $ {UserInfo.location} < - throws error。 我需要訪問該位置。 – user1161505

0

正確的語法應爲:

var result = [ 
    {"Name": "name1", "Type": "type1", "UserInfo": {"date":"123", "location": "earth"}}, 
    {"Name": "name2", "Type": "type2", "UserInfo": {"date":"456", "location": "mars"}} 
]; 

你可以這樣訪問它:

alert(result[1].UserInfo.date); //"456" 

這也適用:

alert(result[1]['UserInfo']['date']); //"456" 

看到它的工作here

+0

再次,我嘗試訪問數組成員的上下文是一個jQuery模板,而不是純javascript。 – user1161505

+0

jQuery和它有什麼關係? – cambraca

+0

你說'$ {UserInfo}'返回一個對象,試試'$ {UserInfo} .location' – cambraca