One of the most useful higher order functions in JavaScript is the filter functions. This function goes through an array and returns true or false based upon the provided argument. I'll use my project for Flatiron below to illustrate how I used the fetch in combination with the filter function to quickly sort through comments and display them all on the front end without a need for a page refresh.
First, I'll fetch the JSON and then pass each object into a new array. This will be the array that we call .filter on in the next step.
Now that the commentArray is set up, we need to filter each comment by it's message_id property. I did this by passing each ID with a "button onclick" that's generated when the messages themselves are initially fetched. As each Message JSON is parsed and rendered the message.id property is stored as message_iid and passed to the function on the button itself. Clicking on the button will launch the next function, showComments.
**Useful tip: Note below that the inline button onclick html below is followed by "return false;". This does the same thing a Event.preventDefault( ), but is a bit cleaner in my opinion since the button and event are already in the same line.
Once we have our array and the info we need to filter it, we can build out a function that will filter the array and then hot load the HTML into the DOM.
Note that the result is the return when the filter is applied to the commentArray, then each comment in the array is checked to see whether it's message_id is equal to the input specified by the onclick event from the button. From there I used forEach to iterate over each result object and inject a fresh div into the html of the page.
link to this project's repo @github


Comments
Post a Comment