In this lesson I am taking in JSON data and am using .filter() on the search <input> to display and pair down the list.
First I create a variable 'endpoint' that holds the URL for the JSON data. I also initialise an empty 'cities[]' array.
I fetch() the JSON data (fetch(endpoint)). fetch() is a promise, which I return .then() on. .then() takes the blob data I receive through the fetch, and converts it to JSON using the .json() method. .json() itself is also a promise which I return another .then() on. The second .then() spreads the data into 'cities[]'' (cities.push(...data)).
I listen for a 'change' or 'keyup' event on the search input, and run displayMatches().
In displayMatches() - Take the value of the search input, and find matches in 'cities[]' (findMatches(this.value, cities)). Then .map() over the array, using a regular expression on the 'city' and 'state' to find matches from the search. Then .replace() the search text, nesting it in a <span> to create the highlight effect on the search term.
Finally, return a <li> for each match into the array. Inject each <li> with values from the JSON using es6 template strings. Finally .join('') the array into one string and pass the string into the .innerHTML of the 'suggestions' element.
See the Pen
JavaScript30 - 6 - Type Ahead by Corey Noble (@CoreyNoble)
on CodePen.