Hi, I am using “fetch” method with API for my website, and this API shows book information, if books include the input title.
Screenshot attached is console.log result when typing an example book title. I’d like to get every title info of each array, could anyone can help me on this?
Especially I am not sure what is the proper line for this.
.then((data) => {document.getElementById("bookinfo").innerHTML= data['documents'.authors];
Entire script for fetch is below.
<script> function getBook(){ let bookvalue=document.getElementById("book").value; fetch('https://dapi.kakao.com/v3/search/book?target=title&query=' + bookvalue, { headers: { Authorization: "KakaoAK TokenID" } }) .then((response) => response.json()) .then((data) => {document.getElementById("bookinfo").innerHTML= data['documents'.authors]; }); } </script>
Advertisement
Answer
You’re not calling the array index correctly, data[‘documents’.authors] should be data.documents[0].authors
to get the author of the first item and data.documents[1].authors
to get the second, etc…
What do you intend to do with the titles?
EDIT: Fixed it for easier use (I think this is what you want)
.then(data => data.documents.map(book => book.title)).then(titles => document.getElementById("bookinfo").innerHTML = titles.join(", "));
Otherwise create an array
const titles = [];
push into array
.then(data => data.documents.map(book => titles.push(book.title))
But you might have issues with this and get empty array since the promise might still be pending