2017-08-26 299 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