I have to get the character names(not URLS) as the output at the $(obj.characters) But I am unsure about how to implement it. I also need five names only using for loop. I have these two problems to clear.
API: https://www.anapioficeandfire.com/api/books
document.body.innerHTML=`<div class="heading-container">
<h1>An Ice and Fire<h1>
</div>
<div id="mainContainer" class="main-container"></div>`;
const getData=async() => {
try{
const data=await fetch("https://www.anapioficeandfire.com/api/books")
const books= await data.json()
mainContainer.innerHTML="";
books.forEach(book => {
displayData(book)
});
}catch(error) {
console.log(error)
}
};
getData();
const displayData=(obj)=> {
mainContainer.innerHTML+=`
<div class="container">
<h1 class="css1">Name:<span>${obj.name}</span>, ISBN:<span> ${obj.isbn}</span></h1>
<h2 class="css2"> Authors:<span>${obj.authors}</span></h2>
<h3 class="cs3"> Number of Pages:<span>${obj.numberOfPages}</span><h3>
<h4 class="css5">Publisher Name:<span>${obj.publisher}</span> , Release Date:<span>${obj.released}</span></h4>
<h4 class="css6">Characters${obj.characters}</span></h4>
</div>`
}
In my humble opinion, you have things too single-use. My implementation is creating a generic "getUrl" to get any resource from your chosen API, which can then be reused to iterate through characters when you need to.
Observe:
const books = [];
getUrl = async(url) => {
try {
const data = await fetch(url);
return await data.json();
} catch (error) { console.log('Failed to retrieve data: ', error); }
}
getBooks = () => {
getUrl("https://www.anapioficeandfire.com/api/books").then(data => {
data.forEach(b => {
const book = { Name: b.name, ISBN: b.isbn, Authors: b.authors, Pages: b.numberOfPages, Publisher: b.publisher, Released: b.released };
let characters = [],
charLen = b.characters.length >= 5 ? 5 : b.characters.length;
for (let i = 0; i < charLen; i++) {
getUrl(b.characters[i]).then(c => characters.push(c.name));
}
book.Characters = characters;
books.push(book);
});
});
}
getBooks();
console.log(books);
This will create a constant books object which will service your needs in your displayData function above (with capitalized property names). It is my opinion that you should also unpack the Authors and Characters lists using <ul><li> since the data may not be presented as aesthetically pleasing as you might expect with your current markup.