2017-08-26 250 views
0

我很困惑,爲什麼這被指定爲「undefined」。任何幫助將非常感謝,因爲我被困在一個重要的項目。JSON對象返回爲undefined

的JavaScript

$.getJSON("item-data.json", function(results) { 
     $.each(results, function(index) { 
      alert(results[index].CatalogEntryView); 
     }); 
    }); 

JSON數據是一個大的文件。它首先將第一個對象定義爲「CatalogEntryView」,並帶有一長串嵌套屬性。

{ 
    "CatalogEntryView": [ 
    { 
     "CustomerReview": [ 

使用下面的答案的一個建議下面的代碼返回以下控制檯:如果我理解正確的,你

推薦碼

$.each(results.CatalogEntryView, function(index, item) { 
     console.dir(item.CustomerReview); 
}); 

Console Output in Chrome

+0

我們需要更多關於JSON文件的結構以及「返回」是什麼意思的信息。 –

+0

它警告「未定義」 – SDH

+0

如果它始於'CatalogEntryView',那麼'index'就是這樣。因此'results [index]'將成爲'results ['CatalogEntryView']'因此'results ['CatalogEntryView']。CatalogEntryView'沒有定義,因爲沒有這樣的屬性 –

回答

1

,嘗試這個:

$.each(results.CatalogEntryView, function(index, item) { 
     console.dir(item.CustomerReview); 
}); 

它應該適合你的json文件的結構。另一個問題是你真的想...

results從你的代碼應該是iterable

jQuery.each(數組,回調) - 一個通用的迭代函數,可用於無縫在對象和數組上迭代 。具有長度屬性 (例如函數的參數對象)的數組和類似數組的對象通過數字索引(從0到長度-1)迭代 。其他對象通過 它們的命名屬性進行迭代。

+0

我將編輯帖子以顯示在控制檯中顯示的內容 – SDH

+1

@SDH我檢查了它。那有什麼問題?它顯示來自'「CustomerReview」'數組的項目。如果你想要更高一層 - 來自''CatalogEntryView''的數組 - 只輸出'item'就像'console.dir(item)'。 – curveball

+0

'{...}'定義了深度/嵌套的級別,即使它沒有名稱。 – curveball