mal*_*ala 2 javascript object joi
我有一个这样的 joi 架构
const userModel = Joi.object({
id: Joi.string().min(3).max(50),
username: Joi.string().min(10).max(100)
... other 10 properties
})
Run Code Online (Sandbox Code Playgroud)
问题是我想获得所有键的值,例如
["id","username",...]
我尝试使用 Object.keys(userModel),但它返回了一个意外的值,如
[
"isJoi",
"_currentJoi",
"_type",
"_settings",
"_baseType",
"_valids",
"_invalids",
"_tests",
"_refs",
"_flags",
"_description",
"_unit",
"_notes",
"_tags",
"_examples",
"_meta",
"_inner"
]
Run Code Online (Sandbox Code Playgroud)
小智 5
出现意外行为的原因是因为 userModel 不是普通对象,而是 joi 对象。
一种可能的解决方案是检查userModel._ids._byKey.keys()以获取模式中所有键的 Map 迭代器。此解决方案的问题在于您依赖 Joi 框架的内部结构。
我可能会建议另一种方法:在单独的数据结构中提取所需的字段 - 数组或对象,并基于此扩展 Joi 模式。
小智 5
const userModel = Joi.object({
id: Joi.string().min(3).max(50),
username: Joi.string().min(10).max(100)
});
const keys = Object.keys(userModel.describe().keys);
console.log(keys)
Run Code Online (Sandbox Code Playgroud)