Reputation: 229
I'm trying to iterate through the list of industryIdentifiers and save the type and identifier values.
I've tried using the following code, but am getting an undefined as the output.
var url = "https://www.googleapis.com/books/v1/volumes/EXiMZwEACAAJ";
$.getJSON(url, function(data) {
var bookID = data.items[0].id;
var title = data.items[0].volumeInfo.title;
var industryIdentifiers = data.items[0].volumeInfo.industryIdentifiers;
$.each(industryIdentifiers, function(result){
var idType = result.type;
var idValue = result.identifier;
alert (idType + " = " + idValue);
});
});
Upvotes: 0
Views: 1025
Reputation: 411
You have two problems. The first issue is that data.items is undefined, for accessing the properties in that data object you have to do this data.nameOfProperty. Your second issue is that when you are iterating through the industryIdentifiers you have to declare a second argument to the anonymous function in the $.each call. Since the first argument is only the index of the array and the second argument is the value of the element, in this case it would be the object that has the properties of type and identifier.
Upvotes: 0
Reputation: 775
Try this code...
$(document).ready( function() {
var url = "https://www.googleapis.com/books/v1/volumes/EXiMZwEACAAJ";
$.getJSON(url).done(function( data ){
var bookID = data.id;
var title = data.volumeInfo.title;
var industryIdentifiers = data.volumeInfo.industryIdentifiers;
//console.log(industryIdentifiers);
$.each(industryIdentifiers, function(i, item){
console.log(item);
var idType = item.type;
var idValue = item.identifier;
alert (idType + " = " + idValue);
});
});
});
Fiddle: http://jsfiddle.net/v5cornfb/
Upvotes: 0
Reputation: 5224
It is because you are wrongly using $.each, $.each has following callback structure ,
callback
Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every object.
So, simply using ,
$.each(industryIdentifiers, function(result){
will produce result as index instead of your sought out value. Thus giving you the undefined
values.
Here is the working code,
var url = "https://www.googleapis.com/books/v1/volumes/EXiMZwEACAAJ";
$.getJSON(url, function(data) {
var bookID = data.id;
var title = data.volumeInfo.title;
var industryIdentifiers = data.volumeInfo.industryIdentifiers;
$.each(industryIdentifiers, function(index,value){
var idType = value.type;
var idValue = value.identifier;
alert (idType + " = " + idValue);
});
});
And, you can view the demo here.
And , also you are wrongly accessing the result JSON. Since it is returning a single value you can directly access it as data.id
.
Upvotes: 1