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 am experiencing difficulty transmitting POST variables using JSON

I'm currently in the process of developing an Android application that communicates with a server using JSON. However, I've encountered a strange issue. My app has a list of questions that need to be synchronized with the server's question ...

Using the .each method in AJAX JQUERY to iterate through callback JSON data and applying an if statement with Regular Expression to identify matches

Implementing a live search feature using ajax and jQuery involves running a PHP script that returns an array of database rows, encoded with JSON, based on the textfield input. This array is then iterated through in JavaScript after the callback function. ...

The Art of jQuery Data Processing

I'm currently working on extracting data from a form submission. Below is the code I've been using. function handleSubmission() { $("#questionForm").submit(function() { $.post("SubmitQuestion.php", $("#questionForm").serialize()).done(functi ...

The issue arises when interfaces are extended by another interface

Is there a way to have classes that implement both the Observer and Comparable interfaces together? interface Comparable<T> { equals: (item: T) => boolean; } interface Observer extends Comparable<Observer> { notify: () => void } ...

Observable task queuing

Here's the scenario: In my application, the user can tap a button to trigger a task that takes 2 seconds to complete. I want to set up a queue to run these tasks one after another, in sequence. I am working with Ionic 3 and TypeScript. What would be ...

Handling private _id fields from MongoDB in Dart's JSON serialization process

I have been utilizing automatic serialization/deserialization in Dart as outlined here import 'package:json_annotation/json_annotation.dart'; part 'billing.g.dart'; @JsonSerializable() class Billing { Billing(){} String _id; St ...

An item whose value is determined by the specific type of key it possesses

Consider the following scenario: enum MouseType { GENERAL_USE = 1, SPECIALIZED_USE = 2, } enum KeyboardType { GENERAL_USE = 3, SPECIALIZED_USE = 4, } interface MouseSpecifications { buttons: number; dpi: number; } interface KeyboardSpecifica ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

The object's null status remains uncertain even after being checked for null

Currently, I am working with Typescript 2.8 This is the code snippet that I have: class Wizard extends React.Componenet { private divElement: null | HTMLDivElement = null; componentDidUpdate(_: IWizardProps, prevState: IWizardState) { i ...

Flask response fails to retain non-visible characters in string

My Python string variable has a unique format: '\x1d0103671286378126378127812\x1d1232321102I009B\x1d71012321271' When I send it in a json response, the \x1d characters disappear. Strangely enough, when I print it on the con ...

What is the best way to assign specific JSON data "values" to named $scope variables in Angular when retrieving data from a SPARQL query?

As a newcomer to Angular, I apologize if my question seems ignorant. I have searched through dataversity, stack overflow, google ... as well as w3c and tried various "try it and see solutions," but I just can't seem to make this work. Essentially, I ...

This property cannot be found on the specified type

So, I have this TypeScript function that will return one of two different objects based on the input value: function myfunc(isError:boolean): {response:string}|{error:string} { if(isError) return {error:''} return {response:''} } N ...

What is the process for refreshing and creating new markers on a Leaflet map?

Recently, I came across Leaflet and decided to use it instead of Google Maps. I have an API that I want to use for generating and updating map markers to prevent having multiple markers. I've been working on a project which you can view in this fiddle ...

Encountering an issue: The type '{ children: Element; }' does not share any properties with type 'IntrinsicAttributes & CookieConsentProviderProps'

I recently updated my packages and now I'm encountering this error. Is there a way to resolve it without reverting back to the previous versions of the packages? I've come across similar errors reported by others, but none of the suggested solut ...

Extracting Node.js data within a Node.js script

Can a node.js file be parsed to execute part of the code within another node.js file? I am attempting to parse a node.js file from within a different script. I do not have control over the contents of the file, but it always contains a function called get ...

Generating fake data using JSON schema patternsfaker

Utilizing the json-schema-faker tool alongside Faker has been instrumental for generating random "real" format values such as emails and image URLs. The current schema I am working with is as follows: { "type": "object", "properties": { "myPatte ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Do we still need Jackson's @JsonSubTypes to perform polymorphic deserialization?

Serialization and deserialization of a class hierarchy can be achieved where the abstract base class is annotated with @JsonTypeInfo( use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") without inclu ...

Tips for sending just the updated section of the form

I am working with a form group where I map the values from the form to an object type in order to make a request to edit the item. This is my form structure: public companyForm = new FormGroup( { generalInfo: new FormGroup({ name: new ...

Where can I locate information on using the .get method?

Recently, I encountered a code snippet on this site that helped me resolve an issue. The individual who provided the code utilized a .GET method that was unfamiliar to me. Here's a sample snippet: If you'd like to see the complete code, you can ...