[英]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.我有一个来自第三方 API 的类型,它有很多属性(50+),它们将所有值都作为字符串。 The even number and booleans became strings ("5" and "false" respectively) and I want to fix the scary thing.
偶数和布尔值变成了字符串(分别是“5”和“false”),我想解决这个可怕的问题。
So I created a type like this to receive the response from API and to hold after fix所以我创建了一个这样的类型来接收来自 API 的响应并在修复后保留
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.您可以对数组进行循环,检查 element.age 是否为字符串,如果是,则解析年龄并再次设置。 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只要变量约定与 person1、person2、person3 等一致,这就应该起作用,并且您还需要知道添加的总人数才能使 forloop 起作用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.