organize and identify a JSON data using sorting and matching techniques

Having a JSON structure as shown below:

[
    {
        "id": "1",
        "freq": "1",
        "value": "Tiruchengode",
        "label": "Tiruchengode"
    },
    {
        "id": "2",
        "freq": "1",
        "value": "Coimbatore",
        "label": "Coimbatore"
    },
    {
        "id": "3",
        "freq": "1",
        "value": "Erode",
        "label": "Erode"
    },
    {
        "id": "4",
        "freq": "1",
        "value": "Madurai",
        "label": "Madurai"
    },
    {
        "id": "5",
        "freq": "1",
        "value": "Salem",
        "label": "Salem"
    },
    {
        "id": "6",
        "freq": "1",
        "value": "Tiruchirappalli",
        "label": "Tiruchirappalli"
    },
    {
        "id": "7",
        "freq": "1",
        "value": "Tirunelveli",
        "label": "Tirunelveli"
    }
]

Seeking to pattern match based on the "label" item in this JSON data. For example, when typing tiru, the result should display label items containing tiru substrings. If it's a single item array, I understand how to perform pattern matching and sorting. However, I am unsure of how to achieve this with multiple items in the array using the label element for comparison. Is this achievable with Pure JavaScript? Any guidance or assistance is appreciated.

Answer №1

To search for specific items in an array using JavaScript 1.6, you can utilize the functional array methods like filter:

var searchTerm = 'apple';
var resultsArray = object.filter(function(item) {
    var firstItem = item.type.toUpperCase();
    var secondItem = searchTerm.toUpperCase();
    return firstItem.indexOf(secondItem) >= 0;
});

If you are interested in retrieving only labels from the filtered results, you can use map to extract that property specifically:

var extractedLabels = object.filter(function(item) {
    var firstItem = item.label.toUpperCase();
    var secondItem = searchTerm.toUpperCase();
    return firstItem.indexOf(secondItem) >= 0;
}).map(function(item) {
    return item.label;
});

In summary, filter is a method accessible to all instances of Array, allowing you to create a new Array with elements that meet certain criteria defined by a supplied function.

Answer №2

To convert the jsonString into a JsonObject, you can utilize JSON.parse(). Once converted, iterate through the object and use indexOf for pattern matching.

var jsonString = '[{"id": "1","freq": "1","value": "Tiruchengode","label": "Tiruchengode"},{"id": "2","freq": "1","value": "Coimbatore","label": "Coimbatore"},{"id": "3","freq": "1","value": "Erode","label": "Erode"},{"id": "4","freq": "1","value": "Madurai","label": "Madurai"},{"id": "5","freq": "1","value": "Salem","label": "Salem"},{"id": "6","freq": "1","value": "Tiruchirappalli","label": "Tiruchirappalli"},{"id": "7","freq": "1","value": "Tirunelveli","label": "Tirunelveli"}]';

    var jsonObjects = JSON.parse(jsonString);       
    var pattern = "tiru";

    for(var key in jsonObjects){
        var label = jsonObjects[key].label.toUpperCase();       
        if(label.indexOf(pattern.toUpperCase()) != -1){
            document.write(label+"<br/>");
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adapting the position of a floating div according to its height and environment

Important Note: The code below utilizes the rubuxa plugin for handling JS sortables. Javascript: function querySelector(expr){return document.querySelector(expr)} var container = querySelector('.ITEST'); var sortable = Sortable.create(container, ...

ways to halt a noise once an animation is complete

I don't have much experience with coding in general, but somehow I've made it this far. Now I'm stuck on the final piece of the puzzle. This is related to a Twitch alert that I'm setting up through 'Stream Elements'. The iss ...

Steps for combining TypeScript and JavaScript into a single file with npm scripts

Check out my complete package.json file here. "scripts": { "build": "webpack", "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"", "lite": "lite-server", "postinstall": "typings install", "tsc ...

Setting up an SSL certificate for an Express application: A step-by-step guide

I am currently trying to set up my Express server in order to pass the SSL certificate and transition from http to https. After going through the Express documentation, I still haven't been able to find a suitable solution. While some suggestions lik ...

Having trouble loading my script in the frontend plugin?

After much testing, I have discovered that when I place this code before the get_header() function, the script is successfully loaded. However, when I move it after the get_header() function, it no longer works as intended. It's important to note that ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

The current export script is experiencing difficulties when working with the next/image component

I am working on a project that I need to build and export, but I am facing an error during the process. Below is the build script found in my package.json file: "scripts": { "build": "next build && next export" } ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

Error: Attempting to access index '0' of an undefined property in firebase and vuex

When using a vuex action to upload an image to Firebase and save the URL, everything seems fine until trying to retrieve the downloadUrl and adding it to the meetup database reference. The code I have looks like this: actions: { createMeetup ({commit ...

Adding Firebase Authentication to my AngularJS website

I am currently creating a school website using AngularJS. My goal is to incorporate account functionality through firebase authentication. However, I have limited experience with Javascript and find working with AngularJS and implementing firebase to be ...

Tips for preserving data while attempting to access the schema

Attempting to store data from a book that includes author and genre information, referenced in separate files. The issue arises when making the reference in the main schema. Although the book carries details of the book itself, it fails to establish refer ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

The implementation of a universal translation system in Express JS

I have developed a straightforward translation module for Express JS. It exists as a global object in the application scope and is initialized during application runtime: translator.configure({ translations: 'translations.json' }); I have i ...

Embed information from a MySQL database into an HTML layout

I have a main webpage containing various links (e.g. fist_link, second_link, etc...) When a user clicks on any link, it should open blank_template.html. If the user clicks on fist_link, the template should display the first string from the database table. ...

Having an issue with ng-model not functioning correctly in md-menu with AngularJS material

I'm currently using md-menu from Angular Material and I have integrated a search box with ng-model in the list. However, I am facing an issue where I cannot access ng-model because 'md-menu-content' is out of scope. Here is my code: <div ...

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

Navigating through JSON data with unspecified keys and fields

I encountered an example of JSON in the front-end: { "properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"} } Trying to parse it using map[string]interface{} proved ineffective. ...

Exploring JSON object lists with JQuery in a Map created using Scala Play 2.0

In my Play Controller, I have the following Scala code (simplified for brevity): object Sample { def apply(someArgToBeUsedLater: String) = { val success = Map("foo" -> List("Things", "Stuff", "Test")) Ok(Json.toJson(success)).a ...

Utilizing ExpressJS to refresh database query after new record insertion

I'm a beginner in using expressJS and I have a question about querying the database (mongo in this case) to retrieve all records after adding one. exports.get = function (db) { return function (req, res) { var collection = db.get('n ...

Utilizing the Codable protocol to parse a Stock API where dates are utilized as keys

Recently, I've been working on parsing a stock API provided by Alpha Vantage. If you're curious to see what the response looks like, check out this link: API Response Demo In order to handle decoding and encoding, I have established four classe ...