If the condition is met, convert the number in JSON format to text

i have retrieved a JSON array from an API:

items:[{
    Name: "Status"
    Value: "3"
},{

    Name: "Status"
    Value: "2"
}, {
    
    Name: "Status"
    Value: "1"
}]

then I extract the data

if (dataStatus.Name == 'Status')   newDataStatus.Status =  dataStatus.Value;

and display the value in my material table

<ng-container matColumnDef="Status">
                <th mat-header-cell *matHeaderCellDef mat-sort-header> Status </th>
                <td mat-cell *matCellDef="let row"> {{row.Status}} </td>
</ng-container> 

However, only numbers are showing in the status row. How can I change Value:"3" to "complete", Value: "2" to "end", and so on?

Answer №1

if (dataStatus.Type == 'Type') { 
   newType.Type =  ['first', 'second', 'third', 'fourth', 'fifth'][+dataStatus.Number];
}

['first', 'second', 'third', 'fourth', 'fifth']
- list of text values for numerical types. It could be beneficial to store this list in a separate variable or property.

plus sign preceding dataStatus.Number - coerces a string into an integer

-1 - subtracts one

Answer №2

If you're working with Typescript, utilizing an enum allows you to easily access the reverse value since enums are present at runtime.

enum Status {
  NEW = '1',
  END = '2',
  COMPLETE = '3',
}

// later
if (dataStatus.Name == 'Status')   newDataStatus.Status =  Status[dataStatus.Value];

Now, newDataStatus.Status is of type keyof typeof Status.

Ensure that you correctly type dataStatus or cast it as any:

Status[(dataStatus.Value as any)]
in order to avoid TS compiler errors.

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

The length of JSONPath in Javascript is significantly longer, approximately 3000 times lengthier than a traditional loop

I am experiencing performance issues with JSONPath implemented in JavaScript using the Stephan Goessner Library. Below is an example of the JSON structure causing the problem: [ { id:1, name: "lorem", elements: [ ...

Retrieving the return type of generic functions stored in a map

In this unique scenario, I have a dictionary with polymorphic functions that accept the same argument but return different results: const dict = { one: { foo<A>(a: A) { return [a] as const } }, two: { foo<A>(a: A) { ...

Exploring nested JSON objects with Jade and Express

Currently, I'm feeling a bit frustrated as I struggle to find a way to access the "media" content from this specific JSON object using Jade. { "summary":"Jose Mourinho names his Real Madrid side to face Borussia Dortmund in the Champions Lea ...

What is the best way to bypass using an if/else statement in TypeScript when dealing with mocha and returning undefined values

A unique spline able to be intertwined and produce a new version of itself, most of the time. export default class UniqueSpline { public intertwinedCount: number; constructor(parent?: UniqueSpline) { this.intertwinedCount = parent && pare ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Lazy loading in Angular 2 hits a snag when using a module that is shared

After successfully lazy loading my AccountModule, I encountered an issue when adding my SharedModule to it. All of my eagerly loaded modules seemed to be forgotten and I started receiving the following error: The component FoodComponent is not part of a ...

What is the method for updating the value of the Sass variable in Angular 4?

Within the file app.component.scss, there is a variable named $color that has been set to 'red'. What steps can be taken within the file app.component.ts in order to access this variable and change its value to 'green'? ...

Ways to implement logging in an NPM package without the need for a specific logging library

Currently, I am in the process of developing a company npm package using TypeScript and transferring existing code to it. Within the existing code, there are instances of console.log, console.warn, and console.error statements, as shown below: try { c ...

Simulating TypeDI service behavior in Jest

My current setup includes Node with TypeScript, TypeDI and Jest. I've been working on creating services that have dependencies on each other. For example: @Service() export class MainService{ constructor(private secondService: SecondService){} public ...

Detect errors in the `valueChanges` subscription of Firestore and attempt a retry if an error occurs

My Angular app utilizes Firestore for storing data. I have a service set up to retrieve data in the following way: fetchCollectionColors(name) { this.db.collectionGroup('collection-colors', ref => ref.where('product', '==&ap ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

Troubden array filtration in Angular is malfunctioning

I recently developed an angular "filter component" intended to filter an array and display its contents. The keyword used to filter the array, value, is obtained from another component through a service. While the HTML displays both the value and the entir ...

Problem with Angular Slider

I'm in the process of creating a carousel component in Angular, but I'm facing an issue where the carousel is not appearing as it should. Below is the code for my carousel component. carousel.component.html: <div class="carousel"> ...

Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock. I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as ex ...

Undoing alterations to the user interface in Angular 2 after discontinuing bi-directional data binding

UPDATE: Including code for further clarification. client.component.ts import { Component } from "@angular/core"; import { ClientService } from "../services/client.service"; import { Client } from "../types/client"; @Component({ selector: "rpcs-client", ...

Retrieving the parent object of a nested object within a JSON data structure using TypeScript

Is there a way to programmatically retrieve the parent object from a child object? My goal is to dynamically access the value of a property that belongs to the parent of a child object. For instance, in the given JSON data, I am interested in getting the ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

Struggle with utilizing associative array beyond a for loop

I am currently facing a challenge with printing an associative array outside of a loop in PHP. My issue revolves around looping through an array of campaign IDs and using them in a URL for a curl request to fetch JSON data from the server. I then extract t ...

Preserve the varying sizes of ROS messages by storing them in arrays

Utilizing the Ros-Yolo neural network for image recognition, I am seeking a way to store the bounding boxes received through this system in an array. Each position of the array should correspond to the following struct. struct rectangle_box { long x_max; ...

Error in Angular 5: Cannot find property 'then' in type 'Observable<any>'

I encountered the following error message: "[ts] Property 'then' does not exist on type 'Observable'. How can I resolve this issue? Below is my Component code: getUsers(){ this.authService.getUsers().then((res) => { thi ...