我有一个像这样的 joi 模式
const userModel = Joi.object({
id: Joi.string().min(3).max(50),
username: Joi.string().min(10).max(100)
... other 10 properties
})
问题是我想获取所有键的值,例如
["id","用户名",...]
我尝试使用 Object.keys(userModel),但这返回了一个意外的值,例如
[
"isJoi",
"_currentJoi",
"_type",
"_settings",
"_baseType",
"_valids",
"_invalids",
"_tests",
"_refs",
"_flags",
"_description",
"_unit",
"_notes",
"_tags",
"_examples",
"_meta",
"_inner"
]
最佳答案
出现意外行为的原因是 userModel 不是普通对象,而是 joi 对象。
一个可能的解决方案是检查userModel._ids._byKey.keys()
以获取架构中所有键的Map迭代器。此解决方案的问题在于您依赖 Joi 框架的内部结构。
我可能会建议另一种方法:在单独的数据结构(数组或对象)中提取所需字段,并基于此扩展 Joi 模式。
<小时/>关于javascript - 如何获取 joi 模式中的所有键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58269607/