-1

Trying to figure out why values in a key value pair of an object show as undefined when being displayed in HTML.
The JSON code is as followed:

{"products" : [
    {
      "name" : "-------",
      "id" : " --------",
      "price" : "---------",
      "description" : "--------"
    },
    {
      "name" : "-------",
      "id" : " --------",
      "price" : "---------",
      "description" : "--------"
    }
]}

HTML code:

<div id="speakerbox">
  <h1>title</h1>
  <div id="object"></div>
</div>

js code:

$.getJSON( 'products.json', function (products) {
    console.log(products);
    var output = '<ul>';
    $.each(products, function (key, val) {
         output += '<li>' + val.id + '</li>';
    });
    output += '</ul>';
    $('#object').html(output);
});

If I use the console.log() method I can see the objects when I debug in chrome however instead of seeing the value, in its place in HTML it outputs "undefined". When i run the js through an online validator it tells me the following: '$' was used before it was defined for these code pieces

$.getJSON( 'products.json', function (products) 
$.each(products, function (key, val) 
$('#object').html(output)

Is there a problem with my function calls? New to JSON so not sure why its doing this. Any help will be appreciated.

1 Answer 1

1

products will contain an object that looks like this:

{"products" : [ ... ]}

The variable you've called products is and object. It contains a property also called products which has a value that is an array. To access it you need products.products.

To iterate over it, you need $.each(products.products in place of $.each(products.

For this reason, it's probably better to call your variable response. It makes much more sense to say response.products than products.products.

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

2 Comments

I'm sorry. I'm having difficulty understanding the difference between the products object and products property and where the difference lies within the code. I'm under the impression that I'm naming an object "products" that contains an array of objects with different key value pairs. Is the "products" property defined in the js?
After further review I can traverse the logic now. Thank you for your response.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.