2013-03-05 44 views
0

我解析了一個合法的JSON對象,我正在遍歷多維數組,先找到基於函數參數的年份,然後當年的月份。Javascript和Parsed JSON - 子節點的['@attributes']。type返回undefined

我的for循環嵌套:

for (year in yearsData) { 
     //If we've found the correct year... 
     if (yearsData[year]['@attributes'].name == yearToGet) { 

     //...walk through that year's child months 
     for (month in yearsData[year]) { 

      //This works! 
      console.log(yearsData[year][month]); 

      //This also works! 
      console.log(yearsData[year][month]['@attributes']); 

      //This does not work! ..but this is what I need! 
      console.log(yearsData[year][month]['@attributes'].name); 
     }  
    } 

我可以跟蹤在Firebug的控制檯中的對象(有效輸出)一路攀升至

的console.log(yearsData [年] [月] [ '@屬性']);

但一瞬間,我在末尾添加類型(.NAME):

yearsData [年] [月] [ '@屬性']是不確定的。

console.log(yearsData [year] [month]);返回有效的對象,並且我可以參見列出的有效@attributes。

我檢查了多次拼寫;我已經將屬性的名稱更改爲其他的東西,以防與年份的屬性發生衝突......但我沒有得到任何答案。

我錯過了什麼簡單的東西?

的JSON:

{ 
"year": [ 
    { 
     "@attributes": { 
      "name": "2013" 
     }, 
     "month": { 
      "@attributes": { 
       "name": "January" 
      }, 
      "winner": "None!", 
      "theme": "Nobody!" 
     } 
    } 
] 

}

+1

你應該包含一部分與問題相關的JSON – srosh 2013-03-05 19:07:50

+1

console.log(yearsData [year] [month])的輸出是什麼? – Mathletics 2013-03-05 19:09:12

+0

我編輯了上述內容以包含JSON。 console.log(yearsData [year] [month])的輸出,在for(in ..)循環中是月份數據,包括屬性和子級。 – Kate 2013-03-05 19:23:06

回答

0

考慮使用jQuery.grep或jQuery.each到對象上的迭代和分析有效地工作。它可以幫助很多。

http://api.jquery.com/jQuery.grep/

+0

對不起,我沒有這個特定項目的選項。 – Kate 2013-03-05 19:24:29

0

一些brainbashing之後,它竟然是一個超級DERP。我使用月份變量而不是字符串'月'來識別它。我需要使用:console.log(yearsData [year] ['month'] ['@ attributes']。name);

爲了得到它。喔。