Reputation: 151
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.
Upvotes: -1
Views: 60
Reputation: 239311
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
.
Upvotes: 1