Creating Dynamic filtering using JSON

PHOTO EMBED

Mon Dec 09 2024 21:19:55 GMT+0000 (Coordinated Universal Time)

Saved by @davidmchale

import data from "./data.json"; // this is the json data

// the json data looks like this

{
  "locations": {

    "brisbaneCityLibrary": {
      "name": "Brisbane City Library",
      "lat": -27.4710107,
      "lng": 153.0234489,
      "website": "https://www.brisbane.qld.gov.au/facilities-recreation/cultural/brisbane-city-library",
      "tel": "+61 7 3403 8888",
      "email": "library@brisbane.qld.gov.au",
      "category": "Library"
    },
    "goldCoastCommunityCentre": {
      "name": "GoldCoast Community Centre",
      "lat": -28.016667,
      "lng": 153.399994,
      "website": "https://www.goldcoast.qld.gov.au/community/community-centres",
      "tel": "+61 7 5667 5973",
      "email": "community@goldcoast.qld.gov.au",
      "category": "Training"
    },
  }

(function () {
  "use strict";

  // Variables
  const dummyData = data.locations; // this pulling the locations from the json data
  const checkboxesWrapper = document.querySelector(".checkers");
  const list = document.querySelector(".filtered-list");
  let filteredItems = [];
  let selectedCategories = [];

  // Get specific data needed from the API and return a new array of data
  function getListData(data) {
    if (!data) return [];
    return Object.entries(data).map(([index, item]) => ({
      name: item.name,
      category: item.category,
      web: item.website,
    }));
  }

  // Generate HTML for each item
  function itemHTML({ name, category, web }) {
    return `
      <li>
        <h3>${name}</h3>
        <p>Category: ${category}</p>
        <p>Website: <a href="${web}" target="_blank" rel="noopener noreferrer">${web}</a></p>
      </li>`;
  }

  // Generate HTML for checkboxes
  function checkboxHTML(category) {
    return `
      <label>
        <input type="checkbox" class="filter-checkbox" name="checkbox" role="checkbox" value="${category}"/>
        ${category}
      </label>`;
  }

  // Display checkboxes in the DOM
  function displayCheckBoxes(array) {
    const data = getListData(array);
    console.log(data);
    const allCategories = data.map((item) => item.category).filter(Boolean);
    const categories = [...new Set(allCategories)]; // Remove duplicates and ret

    const checkBoxHTML = categories.map(checkboxHTML).join("");
    checkboxesWrapper.innerHTML = checkBoxHTML; // Replace content
  }

  // Display items in the DOM
  function displayitems() {
    const itemData = getListData(
      filteredItems.length > 0 ? filteredItems : dummyData
    );

    const listHTML = itemData.map(itemHTML).join("");
    list.innerHTML = listHTML; // Replace content
  }

  // Check if a value exists in an array
  function isValueInArray(array, valueToCheck) {
    return array.some((item) => item === valueToCheck);
  }

  // Handle checkbox changes
  function onHandleCheck(box) {
    if (!box) return;

    box.addEventListener("change", function (e) {
      const { currentTarget } = e;
      const catValue = currentTarget.value.toLowerCase(); // Get the category value from the checkbox clicked
      const isChecked = currentTarget.checked; // Get true or false if the checkbox is clicked or not

      const isExisting = isValueInArray(selectedCategories, catValue);

      console.log({ catValue, isChecked, isExisting });

      // Add to array if checked and not already existing
      if (isChecked && !isExisting) {
        selectedCategories.push(catValue);
      }

      // Remove if unchecked and category exists
      if (!isChecked && isExisting) {
        selectedCategories = selectedCategories.filter(
          (cat) => cat !== catValue
        );
      }

      console.log({ selectedCategories });

      // Filter items based on selected categories
      filteredItems = Object.values(dummyData).filter((item) =>
        selectedCategories.includes(item.category.toLowerCase())
      );

      // Update the displayed items
      displayitems();
    });
  }

  // Initialize the application
  function init() {
    // Initially populate checkboxes based on all categories from dummyData
    displayCheckBoxes(dummyData);
    // Initially populate the list of items based on dummyData
    displayitems();

    const domCheckBoxes = document.querySelectorAll(".filter-checkbox");
    if (!domCheckBoxes) return;
    domCheckBoxes.forEach(onHandleCheck);
  }

  init();
})();
content_copyCOPY

Using the 'category' from the json data to output a list of dynamic checkboxes and filtering out the items when a checkbox is clicked. If another category is added, then another checkbox will be created.