What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows:

jsonList= [
{name:'chennai',  code:'maa'}
{name:'delhi',    code:'del'}
....
....
....
{name:'salem',    code:'che'}
{name:'bengaluru',code:'blr'}
}]

My goal is to filter this data based on keys (name, code) and return matching values. For instance, if CHE is provided, I should first check the CODE for matches and then move on to the NAME.

{name:'salem',    id:'che'},
{name:'chennai',  id:'maa'}

While attempting to achieve this, I encountered issues with my code. It seems to only check on the NAME each time it runs.

public filterJson(text){
 this.filteredOptions = this.jsonList.filter(
   e => (
    e.code.toLowerCase().indexOf(text.toString().toLowerCase()) !== -1) ||
    e.name.toLowerCase().indexOf(text.toString().toLowerCase()) !== -1)
   ).slice(0, 9);
}

I also tried using 0 as a test case for filtering:

public filterJson(text){
 this.filteredOptions = this.jsonList.filter(
   e => (
    e.code.toLowerCase().indexOf(text.toString().toLowerCase()) === 0) ||
    e.name.toLowerCase().indexOf(text.toString().toLowerCase()) === 0)
   ).slice(0, 9);
}

If you want to see more details or try out the TypeScript playground link, click here

Answer №1

Here is a corrected version of the code with syntax errors fixed and one additional variable, but no changes to the logic:

var jsonList= [
  {name:'chennai',  code:'maa'}, // commas added
  {name:'delhi',    code:'del'},
  {name:'salem',    code:'che'},
  {name:'bengaluru',code:'blr'}
];

function filterJson(text) {
  const lcText = text.toString().toLowerCase(); 
  return jsonList.filter(
    e => (
      (e.code.toLowerCase().indexOf(lcText) === 0) ||
      (e.name.toLowerCase().indexOf(lcText) === 0)         
    )
  ).slice(0, 9);
}

JSON.stringify(filterJson("che"))

"[{"name":"chennai","code":"maa"},{"name":"salem","code":"che"}]"

Ensure that your code compiles correctly. TypeScript can help catch syntax errors at compile time.

Answer №2

Response provided by @Motti has already been shared :) I just wanted to provide an updated method for sorting, which may be beneficial to someone.

this.jsonList.filter(
      e => (
        (e.code.toLowerCase().indexOf(text) === 0) ||
        (e.name.toLowerCase().indexOf(text) === 0)
       )).sort(
         (a, b) =>
         (
          (a.code.toLowerCase().indexOf(text) === 0) ? -1 :
          (b.code.toLowerCase().indexOf(text) === 0) ? 1 : 0
        )
        )
       .slice(0, 10);

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

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

"Exploring the process of looping through a JSON object following an asynchronous retrieval of JSON data using

I am facing an issue while trying to iterate through a JSON object in jQuery after fetching it asynchronously. I have a function called 'listFiles' that uses async to successfully retrieve a file list from a directory (dir) by calling an API endp ...

Parsing UK Bank holidays data using Pandas

Having trouble reading the JSON file from this link into pandas properly : I attempted to use json_normalize and also tried opening it as a file with the standard python library, converting to dict, and then reading it into pandas. This is the result I&a ...

What is the best method to utilize option/input value to efficiently filter out the corresponding outcomes from a JSON object

This section is where the input value for options needs to be filtered. By entering "Other students", it will filter out the data set, showing only the people who identify as "Other students." import React, { useState } from "react"; import {useNavigate} f ...

JSON - Ensuring unique table names every time

I'm having some issues with JSON handling. Let me share my code here, along with the output it generates and what I want it to display. Here is the snippet of my code: // Establish connection to MySQL database $connection = mysqli_connect("localho ...

The value binding for input elements in Angular 4 remains static and does not reflect changes in the UI

Struggling with binding input to a value in angular 4? Take for example [value]="inputFrom". Sometimes it updates when I change inputFrom, other times it doesn't. How can I ensure the input always changes whenever inputFrom changes, not sporadically? ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

What is the best way to join together the deserialized QnAResponse string instead of using a {filename}?

Within this documentation, there is a demonstration of the QnA Maker service executing REST calls and parsing JSON responses - Step 3: How to link Luis with QnA The specific module section I am referring to looks like this: /* START - QnA Maker Response ...

What is the process for importing XML file data into ArangoDB?

<InputParameters> <Textbox> <Text>1234</Text> <Text>5678</Text> <Text>90AB</Text> </Textbox> </InputParameters> If you need to import the data from this XML file i ...

Using PersistedModel.create(Array) will generate an object containing properties that are numbered sequentially

Here is a piece of code that makes a call to a Loopback API method with an array of values. The input data is correct, no errors are thrown by the API, and the subscribe block executes as expected. const newStudentGroups = selectedStudentI ...

Updating an element within a JSON object in PHP: A step-by-step guide

I have a JSON object that looks like this: { "fields" : [ { "name" : "news_title", "type" : "text", "value" : "old title" }, { "name" : "news_co ...

What is the best way to retrieve JSON values based on a key using JavaScript, jQuery, or AngularJS?

Here is some JSON data that I need help with: var jsonData = { "title": "Testing", "settings": { "mySettings": false }, "jsonList": ["TestingList"], "testJsonVals": { "Test1": { "name": "name1", ...

Leverage the Node Short ID library in conjunction with Angular 6 using TypeScript

I attempted to utilize the node module within an Angular 6 typescript environment. Step one: npm i shortid Within my TypeScript class: import { shortid } from 'shortid'; let Uid = shortid.generate(); However, I encountered an error stating ...

Combine two org.json.JSONObject objects that are nested inside each other

Having two JSON objects from the library org.json, the first one is: json1 = {a: {b : {c: val1} } } and the second one is: json2= {a {b: {c2: val2 } } } I am looking for a way to merge these two objects into one as shown below: result = {a: { b: {c: v ...

Changing a MySQL query result into a JSON format using PHP

Is there a built-in PHP function or class that can convert a MySQL recordset into a JSON string, which can then be used in an Ajax request within a JavaScript function? For example: function convertRecordSetToJson($recordset) { while($row = mysql_fetch_ ...

Issue encountered while accessing theme properties in a ReactJs component with Typescript

I am trying to pass the color of a theme to a component in my TypeScript project (as a beginner). However, I have encountered an error that I am struggling to resolve. The specific error message reads: 'Parameter 'props' implicitly has an ...

Tips for accessing and modifying local files in Angular 2

Is there a method in Angular 2 to access files from an absolute path? I have utilized the 'filesaver' library for file saving, storing the files locally in txt/json formats. For instance: let blob = new Blob([document.getElementById(&apos ...

In Next.js, the switch button remains in the same state even after the page is refreshed

Is there a solution for this issue? I am currently developing a switch button for a configuration page. The problem arises when I toggle the switch from active to maintenance mode, save it successfully, but upon refreshing the page, the switch reverts back ...

Tips on how to update a table following each button click during an ajax request

I am encountering an issue while trying to display data in a table by clicking on a search button. The problem arises when there is no data between the specified "Fromdate - Todate" range; the error message appears correctly. However, even after entering t ...

converting intricate json data into java objects with gson

I have been struggling to convert this JSON into a Java object. Despite trying multiple methods, I have not been successful. Any suggestions on how to accomplish this task would be greatly appreciated! { "id":"100006077890894", "posts":{ "data": ...