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

Time:10-07

I have a type like this

interface Person {
  age: string | number,
  name: string
}

So I could have the following:

const person1: Person = {
  age: 20,
  name: Jonh,
}
const person2: Person = {
  age: "21",
  name: Marie,
}

EDIT: My intention is to iterate over properties of any possible kind of this object (just one object) to standardize all in same way.

OBS: This is an example... My object is much bigger than this, with a lot of props in this situation so treat them individually would be very messy

CodePudding user response:

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
});
    

CodePudding user response:

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);
  • Related