What is the best way to loop through an object in TypeScript and replace a string value with its corresponding number?

My situation involves handling data from a 3rd party API that consists of multiple properties, all stored as strings. Unfortunately, even numbers and booleans are represented as strings ("5" and "false" respectively), which is not ideal. I am determined to rectify this issue.

To address this, I have created a type to receive the API response and store the corrected values:

interface Person {
  age: string | number,
  name: string,
  hasChildren: string | boolean,
  ...
}

My goal is to convert data like this:

const responseFromApi: Person = {
  age: "20",
  name: "John",
  numberOfChildren: "true"
  ...
}

into this format:

const afterTreatment: Person = {
  age: 21,
  name: "John",
  numberOfChildren: true
  ...
}

It's worth noting that my actual object contains many more properties than shown in this example. Therefore, individually addressing each property is not a feasible solution for me.

My plan is to iterate through the object and convert any eligible values to their correct types based on the defined interface.

Answer №1

If you iterate through the array using a for loop, you can check if the element's age is a string and if so, convert it to an integer using parseInt. Alternatively, a more efficient approach would be to use the map method on the list, applying the same logic as before but creating a new array with the updated values.

Here's an example:

const updatedList = people.map((person: Person) => {
  if (typeof person.age === "string") {
    return {
      ...person,
      age: parseInt(person.age)
    }
  }
  return person;
});
    

Answer №2

As long as you maintain consistent variable naming conventions like person1, person2, person3, and ensure you provide the total number of added persons, this code snippet should function correctly.

interface Person {
    age: string | number,
    name: string
}
const person1: Person = {
  age: 20,
  name: "John",
}
const person2: Person = {
  age: "21",
  name: "Marie",
}
const lengthOfPersons: number = 2;
const newArray = [];
for(let i = 0; i < lengthOfPersons; i++)
{
 const n = i + 1;
 const row = eval('person'+n);
 newArray.push({...row, age: +row.age})
}
console.log(newArray);

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

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

How to access a specific element within an ng-grid

My grid options include: $scope.ngOptions = { data: 'data', columnDefs: [ {field: 'Status', displayName: "Status", cellTemplate: selectTableTemplate, enableCellEdit: true}, {cellTemplate: &apos ...

Is there a way to pass around jest mocks across numerous tests?

In my test scenarios, I've created a mock version of the aws-sdk, which is functioning perfectly: jest.mock("aws-sdk", () => { return { Credentials: jest.fn().mockImplementation(() => ({})), Config: jest.fn().mockImplementati ...

Why does AngularJS treat $http response.data as an object, even though PHP sends back a JSON string?

I am struggling with an AJAX call to PHP. The Angular code seems simple: $http( { // ... } ) .then( function cf_handle_success( response ) { console.log( response.data ) ; // --> [object Object] } , ...

Could not locate the express.js file

Currently in the process of learning express/node.js, but struggling to locate the page at localhost:3000/info You can view screenshots of my code below ...

Troubleshooting the Bootstrap4 NavBar toggle button malfunction

When the window is resized, the buttons on the navbar disappear and the toggle button appears but does not function to display the dropdown menu. The jQuery and other links have been copied from the Bootstrap website. <!DOCTYPE html> {% load static ...

Integrate Javascript code into a JavaScript file

Is there a way to incorporate a JavaScript link inside a .js file? Does a .js file support include, require, or import similar to CSS or PHP? Here is the code in question: // Global site tag (gtag.js) - Google Analytics var script = document.createElemen ...

I aim to display interconnected information from various APIs in a cohesive manner

I am working with two APIs: component.ts ngOnInit(): void { this.getQueryCountriesList().subscribe(arg => { this.countryDatas = arg; }); this.getQueryNights().subscribe(obj => { this.nightDatas = obj; }); ...

Error in Angular 2: The requested URL https://imgur-apiv3.p.mashape.com/ cannot be loaded. The use of a wildcard '*' is not allowed in the 'Access-Control-Allow-Origin' header

I'm attempting to upload an image using the imgur API at: . However, I keep encountering this error: XMLHttpRequest cannot load . A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credential ...

Angular developers are struggling to find a suitable alternative for the deprecated "enter" function in the drag and drop CDK with versions 10 and above

By mistake, I was working on an older version of Angular in StackBlitz (a code-pane platform). I came across a function called enter on GitHub, but it didn't solve my issue. I was working on a grid-based drag and drop feature that allows dragging bet ...

Learn the method of exhibiting array elements in a dropdown menu with React JS

I am struggling to display all 12 months in a dropdown using React JS. I have written the code below and used moment.js to fetch the months, which I can see in the console but they are not showing up in my dropdown menu. I tried to use .map() to display t ...

Every time I make updates, I have to reload the page to see the changes take effect

Currently, I am in the process of developing a web application that utilizes Firebase Firestore as the backend and NoSQL database, with Angular serving as the frontend. With frequent updates and changes being made to the website, it becomes cumbersome to c ...

single-spa: revolutionizing console.log for each microfrontEnd

Imagine having multiple single-spa react microfrontend apps in your project, such as Cart and Products The goal is to modify console.log, console.error, etc. so that they include a prefix indicating the corresponding microfrontend app: console.log call ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...

The Axios post .then feature works correctly in Chrome, but it does not behave the same way in Firefox, Safari

When I send a CSV download from my server, I use the following code: $headers = ['Content-Type' => 'application/csv']; return response()->download($filepath, $filename, $headers)->deleteFileAfterSend(true); The download proce ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Ways to incorporate services into functions within Angularjs

I'm struggling to grasp the concept of dependency injection in AngularJS. Currently, I am attempting to inject $interpolate and $eval into my controller. However, after consulting the documentation, I realized that my lack of foundational knowledge i ...

Tips for adjusting the size of Material UI icons

My Material UI icon size doesn't align naturally with the button: https://i.sstatic.net/l1G98.jpg Button code snippet: <Button variant="outlined" startIcon={<FacebookIcon />}> </Button> Here is the complete example ...

Displaying FancyBox iframe on third visit to a page

I have been working on a JavaScript function that increments a cookie value every time a page is visited. What I am trying to achieve is for an iframe FancyBox to open after the third visit. Here is the part of the code where I am currently facing some dif ...

Error encountered while importing ES6 npm module in Meteor causing SyntaxError

I initialized a fresh meteor project by executing the command meteor create Afterwards, I utilized npm install -S spacy-nlp, which includes some ES6 code snippets In the server/main.js file, I included import spacy from 'spacy-nlp' Upon running m ...