我从API (每次一个JS对象)接收数据,并希望检查其中的任何值是否丢失或数据类型是否错误。
是否可以定义类似于模板的内容:例如{"name": String, "Housenumber: "Integer}并检查实际对象是否具有相同的键和数据类型?
发布于 2020-12-02 08:27:11
是的,您可以使用所有的keys和datatypes创建一个对象。在此之后,您只需遍历对象并对照数据检查它。
请注意,使用floats不能检查typeof和integers之间的区别。为此,您需要一张自定义支票。
虽然我建议使用类似于打字脚本的类型检查,因为它有很多内置的功能。
const personInterface = {
name: "string",
age: "number",
};
const persons = [
{
name: "bob",
age: 18,
},
{
name: "karen",
age: "50",
}
];
for(const person of persons) {
for(const [key, value] of Object.entries(personInterface)) {
if(typeof person?.[key] === value) {
console.log(`${person[key]} matches ${value}`);
} else {
console.log(`${person[key]} does not match ${value}`);
}
}
}
https://stackoverflow.com/questions/65104286
复制相似问题