检查复杂 JavaScript 对象的完整性
在 JavaScript 中测试复杂对象完整性的最佳方法是什么?
我的对象有一堆不同的变量,一些是可选的,一些是必需的。正确的结构对于代码的功能至关重要,但如果我在定义过程中犯了错误,找到导致问题的确切值可能会变得非常乏味。尤其是错误消息只会告诉我“在代码中您使用了错误的变量类型!”。
我的对象可能看起来像这样,例如:
{
name:"Test",
categories:{
A:{
depth:1,
groups:{
main:[
{myFunction:funcA, arg:[1,2]},
{myFunction:funcB}
]
}
},
B:{
groups{
main:[
{myFunction:funcC}
],
secondary:[
{myFunction:funcD}
]
}
}
}
}
谢谢!
What is the best way to test the integrity of a complex object in JavaScript?
My object has a bunch of different variables, some optional, some required. The correct structure is vital to the code's functionality, but if I make a mistake during the definition, finding the exact value that caused the problem could get very tedious. Especially with error messages that tell me no more than "Somwehere in the code you're using the wrong variable type!".
My object could look something like this, for example:
{
name:"Test",
categories:{
A:{
depth:1,
groups:{
main:[
{myFunction:funcA, arg:[1,2]},
{myFunction:funcB}
]
}
},
B:{
groups{
main:[
{myFunction:funcC}
],
secondary:[
{myFunction:funcD}
]
}
}
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除了编写一个函数来接收对象作为输入并验证它是否具有“正确”的结构之外,没有什么好方法可以做到这一点。
另一方面,您可以定义一个构造函数,它接受正确构造对象所需的任何参数。
There isn't a good way to do this beyond writing a function that receives an object as input, and verifies that it has the "right" structure.
On the other hand, you can define a constructor which takes whatever arguments you need to construct the object properly.
好的,这就是我解决这个问题的方法:我创建一个对象来定义我的复杂对象应该是什么样子。在某种程度上,是一个蓝图。
然后我运行一个函数,将蓝图(“struct”)与要测试的对象(“def”)进行比较:
比较函数仍在进行中,但这就是我现在要使用的概念。
Okay, this is how I've solved it: I create an object that defines what my complex objects should look like. A blueprint, in a way.
Then I run a function that compares the blueprint ("struct") with the object to be tested ("def"):
The comparison function is still work in progress, but that's the concept I'm going with for now.
您可以尝试根据 JSON 架构
但这可能有点过分了。
You can try to validate your object against a JSON Schema
But this may be an overkill.
您可能会尝试 JSON 架构验证。您可能需要进行一些修改,以考虑到您还可以拥有在 JSON 中无效的函数。
You might be try JSON Schema Validation. You might need some modifications to account for the fact that you can have functions as well which are not valid in JSON.