function attachEvents() { let btnLoadPosts = document.getElementById("btnLoadPosts"); let btnViewPost = document.getElementById("btnViewPost"); let sel = document.getElementById("posts"); let postTitleh = document.getElementById("post-title"); let postBody = document.getElementById("post-body"); let commentsUl = document.getElementById("post-comments"); btnLoadPosts.addEventListener("click", loadPosts); btnViewPost.addEventListener("click", viewPost); let postsObj={} var requestOptions = { method: 'GET', redirect: 'follow' }; function loadPosts() { sel.innerHTML = ""; fetch("http://localhost:3030/jsonstore/blog/posts", requestOptions) .then(response => response.json()) .then(result => {populateSelect(result); postsObj=Object.assign({},result)}) .catch(error => console.log('error', error)); } function populateSelect(o) { let arrOfPosts = Object.entries(o); arrOfPosts.forEach(p => { let post = p[1]; let title = post.title; let opt = document.createElement("option"); opt.value = post.id; opt.textContent = title; sel.appendChild(opt) }); } function viewPost() { let neededId = sel.options[sel.selectedIndex].value; getPostDetails(postsObj,neededId); //get all coments fetch("http://localhost:3030/jsonstore/blog/comments", requestOptions) .then(response => response.json()) .then(result => renderComments(result, neededId)) .catch(error => console.log('error', error)); } function getPostDetails(data, neededId) { //get needed post let arr = Object.entries(data); let post = arr.find(a => a[0] == neededId); postTitleh.textContent = ""; postTitleh.textContent = post[1].title; postBody.textContent = post[1].body; } function renderComments(data, neededId) { commentsUl.innerHTML = ""; let arrData = Object.entries(data); //filter comments let relevantComments = arrData.filter(a => a[1].postId == neededId); relevantComments.forEach(c => { let comLi = document.createElement("li"); comLi.id = c.id; comLi.textContent = c[1].text; commentsUl.appendChild(comLi) }) } } attachEvents();