JavaScript Search in Array Of Objects

JavaScript Search in Array Of Objects
Code Snippet:City search | JS 30
Author: Lukaszewska
Published: January 9, 2024
Last Updated: January 22, 2024
Downloads: 752
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code performs live searches in an array of objects retrieved from a JSON file. The code enables users to input text in a search field, dynamically displaying city or state matches that correspond to the input. It uses regular expressions to filter the matching text in the list and highlights the user’s search input within the results.

The purpose is to assist users in finding words from a dataset of longer text, providing a smooth search experience. The code simplifies the integration of live search features.

How to Create Search In Array Of Objects in JavaScript

1. Start by creating an HTML structure. Define an input field for users to enter their search queries and a container for displaying the search results. You can use the following HTML template:

<form id="search-form">
       <input id="search" type="text" placeholder="Search for cities or states" />
   </form>
   <h6></h6>
   <ul id="search-results">
       
   </ul>

2. Use CSS to style the search input, results container, and the overall layout. The following CSS code contains styling instructions to create a clean and user-friendly interface.

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    color: #636360;
    font-size: 16px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

body {
    background-color: #BDBAA4;
}
#search-form {
    width: 95%;
    margin: 2em auto;
    transition: .5s;
}
input {
    width: 100%;
    background-color: #E3E5D5;
    color: #636360;
    border: none;
    font-size: 16px;
    padding: 1em .5em;
    outline: none;
    border-radius: .3em;
    -webkit-box-shadow: 0px 2px 2px 0px rgba(99,99,96,0.66);
    -moz-box-shadow: 0px 2px 2px 0px rgba(99,99,96,0.66);
    box-shadow: 0px 2px 2px 0px rgba(99,99,96,0.66);
    transition: .6s;
}
input:focus {
    background-color: #EFEFE8;
}
input::-webkit-input-placeholder {
    color: #BDBAA4;
}
input::-moz-placeholder {
    color: #BDBAA4;
}
input:-moz-placeholder {
    color: #BDBAA4;
}
input:-ms-input-placeholder {
    color: #BDBAA4;
}
#search-results {
    width: 95%;
    margin: 2em auto;
    border-top: 1px solid #E3E5D5;
    transition: .5s;
}
h6 {
    text-align: center;
}
.input {
    font-style: oblique;
    font-weight: 400;
}
li {
    padding: 1em .3em;
    list-style: none;
    border-bottom: 1px solid #E3E5D5;
    text-transform: capitalize;
}
.city {
    font-weight: 700;
}
.population {
    float: right;
    font-size: .7em;
    line-height: 1.8em;
    text-transform: lowercase;
}
.highlight {
    background-color: #E3E5D5;
}
@media screen and (min-width: 480px) {
    #search-form {
        width: 80%;
    }
    #search-results {
        width: 80%;
    }
}
@media screen and (min-width: 600px) {
    * {
        font-size: 20px;
    }
    input {
        font-size: 20px;
    }
}
@media screen and (min-width: 800px) {
    #search-form {
        width: 60%;
    }
    #search-results {
        width: 60%;
    }
}
@media screen and (min-width: 1024px) {
    #search-form {
        width: 500px;
    }
    #search-results {
        width: 500px;
    }
}

3. In the JavaScript section, we start by fetching the data. The dataset of cities and states is retrieved from a remote source. You can specify your data source URL in the endpoint variable.

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; //Array of objects
const cities = [];
fetch(endpoint) //zaciagamy dane z linka
    .then(blob => blob.json()) //mówimy, że jest to plik json
    .then(data => cities.push(...data)) //wpychamy do tablicy cities jako osobne elementy dlatego są ...
    .then(all => displayMatches());
function findMatches(input) {
    return cities.filter(place => {
        const regex = new RegExp(input, 'gi') //tworzymy wyrażenie regularne którym jest nasz input, czyli to co wpisze szukający  drugi to:  g - global czyli globalny, i - insensitive (czyli nie zwraca uwagi na wielkość liter)
        return place.city.match(regex) || place.state.match(regex); //zwracamy tablicę pasująych do naszego wyrażenia miast lub stanów
    });
}
function numberWithCommas(a) {
    return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  }
function displayMatches() {
    const input = searchInput.value;
    const matchArray = findMatches(input);
    const htmlMatchArray = matchArray.map(place => {
        const regex = new RegExp(input, 'gi');
        const cityName = place.city.replace(regex, `<span class="highlight">${input}</span>`);
        const stateName = place.state.replace(regex, `<span class="highlight">${input}</span>`);
        return `<li>
                    <p class="city-state"><span class="city">${cityName},</span> ${stateName} <span class="population">population: ${numberWithCommas(place.population)} </span> </p>
                </li>`;
    }).join('');
    const headerText = input ? `${matchArray.length} matches for <span class="input">${input}<span>` : `List of 1000 cities in the USA`;
    searchResults.innerHTML = htmlMatchArray;
    header.innerHTML = headerText;
}

const searchInput = document.querySelector('#search');
const searchResults = document.querySelector('#search-results');
const header = document.querySelector('h6');

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);

That’s all! hopefully, you have successfully created a feature to search in array of objects using JavaScript. This user-friendly feature improves user engagement and navigation, making it a valuable addition to your project. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X