简体   繁体   中英

How to iterate an object on TypeScript changing a string value for its corresponding number?

I have a type coming from a 3rd party API which has a lot of properties (50+) and they take all values as string. The even number and booleans became strings ("5" and "false" respectively) and I want to fix the scary thing.

So I created a type like this to receive the response from API and to hold after fix

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

And I want to transform this

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

to

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

This is an example... My object, again, is much bigger than this, with a lot of props in this situation so treat them individually is not the kind of solution I'm looking for.

My intention is to iterate over the object and change to number or boolean what can be changed following type.

You could for-loop the array, check if the element.age is a string and if yes parseInt the age and set it again. A better solution would maybe be to map though the list, and do the same thing as above, just so it creates a new array, which you could then overwrite/do what you need.

Idea:

const changed = persons.map((p: Person) => {
  if (typeof p.age === "string") {
    return {
      ...p,
      age:parseInt(p.age)
    }
  }
  return p
});
    

This should work as long as the variable conventions are consistent with person1, person2, person3 etc and also you need to know the total number of added persons for the forloop to work

interface Person {
    age: string | number,
    name: string
}
const person1: Person = {
  age: 20,
  name: "Jonh",
}
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM