I have an array of objects that are returned from a fetch() response. I sort them alphabetically and store the sorted array in sortedComments.
The comments have multiple keys, such as linkId, time_created, however I'm just trying to get the body out of each comment and append these to a comments_section div that I have in my view.
Below is my code:
function sortComments() {
$("#sort_comments").on("click", function (e) {
e.preventDefault();
var buttonData = document.getElementById("sort_comments").dataset.linkid
fetch(`/links/${buttonData}/comments.json`)
.then(r => r.json())
.then(comments => {
const sortedComments = comments.sort(({body: a}, {body: b}) => a.localeCompare(b))
console.log(sortedComments)
var $ul = $("div.comments_section ul")
$ul.append(sortedComments.body)
})
})
}
The console.log(sortedComments) shows the array of comments alphabetized, but I don't know which function I need to iterate in the array and get the body of each comment.
I've seen resources online that suggest for..in and object.getOwnProperty but I haven't seen it used on arrays like the one I have.
Any help would be greatly appreciated.
commentsarray?sortedComments.forEach((idx, comment) => console.log(comment.body))as one starting point.