0

I am confused as to why this is alterting as "undefined". Any help would be much appreciated as I am stuck on an important project.

JavaScript

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

JSON Data is a BIG file. It starts out with the first object defined as "CatalogEntryView" with a long list of nested properties.

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

Using the following code recommended in one of the answers below returns the following to the console:

Recommended Code

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

Console Output in Chrome

5
  • We'll need more information on how your JSON file is structured and what do you mean by "returning". Commented Aug 26, 2017 at 23:04
  • It alerts "undefined" Commented Aug 26, 2017 at 23:05
  • If it starts out with CatalogEntryView, then that is what index is going to be. So results[index] is going to be results['CatalogEntryView'] and thus results['CatalogEntryView'].CatalogEntryView is undefined as there is no such property Commented Aug 26, 2017 at 23:05
  • So just alert results[index] instead? Commented Aug 26, 2017 at 23:06
  • Your each function is expecting an array of json objects, but this nested object doesn't seem to be an array. Commented Aug 26, 2017 at 23:07

1 Answer 1

1

If I understood you correctly, try this:

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

It should fit the structure of your json file. Another question is what you really want to get...

results from your code should be iterable:

jQuery.each( array, callback ) - a generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

Sign up to request clarification or add additional context in comments.

4 Comments

I will edit the post to show what showed up in the console
@SDH I checked it out. And what is wrong with that? It shows items from "CustomerReview" array. If you want 1 level higher - items from "CatalogEntryView" array - output just item like console.dir(item).
{...} defines a level of deepness/nesting even if it doesn't have a name.
This was actually really helpful. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.