I'm consuming a Google Books API to display results from a simple book search. However, when performing the search, some items return repeated. See: book-search
To GET this data and display in HTML, I am doing this:
var result = document.getElementById("result");
var cover, title, author, book_id;
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// Create elements
figure = document.createElement("figure");
aEmp = document.createElement("a");
aId = document.createElement("a");
img = document.createElement("img");
figcap = document.createElement("figcaption");
// Get data from JSON
try {
cover = item.volumeInfo.imageLinks.thumbnail;
title = item.volumeInfo.title;
author = item.volumeInfo.authors;
book_id = item.id;
} catch (error) {
continue;
} finally {
// Set value to elements e send to HTML
result.appendChild(figure);
aEmp.appendChild(img);
aId.innerHTML = "ADICIONAR";
aId.href = `/add/${book_id}`;
aId.classList.add("dropdown");
figure.appendChild(aId);
figure.appendChild(aEmp);
img.src = cover;
figcap.innerHTML += `${title}<br>${author}`;
figure.appendChild(figcap);
}
}
}
document.querySelector("form").addEventListener("submit", function (e) {
result.innerHTML = "";
search = document.getElementById("search").value;
var script = document.createElement("script");
script.src = `https://www.googleapis.com/books/v1/volumes?q=${search}&callback=handleResponse`;
document.body.appendChild(script);
e.preventDefault();
});
This is the JSON example used on the image I uploaded:
https://www.googleapis.com/books/v1/volumes?q=$harry+potter&callback=handleResponse
Looks like each of the items in Google's response array includes a unique ID. In your callback function, iterate through the array of returned results; remember ID's that have been seen already in a dictionary/hash table. If an ID that's been seen before is showing up again, just skip over that record.