检查复杂 JavaScript 对象的完整性

发布于 2024-11-07 13:34:10 字数 568 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

会发光的星星闪亮亮i 2024-11-14 13:34:10

除了编写一个函数来接收对象作为输入并验证它是否具有“正确”的结构之外,没有什么好方法可以做到这一点。

function isValid(obj)
{
    if (!o) return false;
    if (typeof o.name !== 'string') return false;
    if (typeof o.categories !== 'object') return false;
    if (typeof o.categories.a !== 'object') return false;
    if (typeof o.categories.b !== 'object') return false;
    // etc...

    return true;
}

另一方面,您可以定义一个构造函数,它接受正确构造对象所需的任何参数。

function MyObj(name, categoryNames /* other args */)
{
    this.name = name;
    this.categories = {};

    for (var i=0; i<categoryNames.length; i++)
    {
        this.categories[categoryNames[i]] =
        {
            groups: {main: []}
        };
    }

    // etc
}

// use it like this:
var foo = new MyObj('Test', ['A', 'B'] /* other args */);

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.

function isValid(obj)
{
    if (!o) return false;
    if (typeof o.name !== 'string') return false;
    if (typeof o.categories !== 'object') return false;
    if (typeof o.categories.a !== 'object') return false;
    if (typeof o.categories.b !== 'object') return false;
    // etc...

    return true;
}

On the other hand, you can define a constructor which takes whatever arguments you need to construct the object properly.

function MyObj(name, categoryNames /* other args */)
{
    this.name = name;
    this.categories = {};

    for (var i=0; i<categoryNames.length; i++)
    {
        this.categories[categoryNames[i]] =
        {
            groups: {main: []}
        };
    }

    // etc
}

// use it like this:
var foo = new MyObj('Test', ['A', 'B'] /* other args */);
伏妖词 2024-11-14 13:34:10

好的,这就是我解决这个问题的方法:我创建一个对象来定义我的复杂对象应该是什么样子。在某种程度上,是一个蓝图。

var structure = {
  property1: {id:"name", type:"string", required:false},
  property2: {
    id:"categories", type:"object", required:true,
    content:{
      property1:{
        type:"object", min:1,
        content:{
          property1:{id:"depth", type:"positiveinteger", required:false},
          property2:{
            id:"groups", type:"object", required:true,
            content:{
              property1:{
                type:"array", min:1,
                content:{
                  type:"object", min:1,
                  content:{
                    property1:{id:"myFunction", type:"function", required:true},
                    property2:{id:"args", type:"array", required:false},
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

然后我运行一个函数,将蓝图(“struct”)与要测试的对象(“def”)进行比较:

function compareStructure(struct, def){
  if(isArray(def)){
    if(isDefined(struct.min) && def.length < struct.min){ alert("Error in structur check: " + " min is " + struct.min + "."); return false}
    if(isDefined(struct.max) && def.length > struct.max){ alert("Error in structur check: " + " max is " + struct.max + "."); return false}
    for(var i = 0; i < def.length; i++){
      compareStructure(struct.content, def[i]);
    }
  } else {
    for(var k in struct){
      if(struct[k].id){
        propFound = false;
        for(var m in def) if(m == struct[k].id) propFound = m;
        if(!propFound && struct[k].required){ alert("Error in structure check:  " + struct[k].id + " not defined."); return false}
        if(propFound && !verifyThis(struct[k], def[propFound], propFound)) return false;
        if(propFound && struct[k].content) compareStructure(struct[k].content, def[propFound]);
      } else {
        for(var m in def){
          if(!verifyThis(struct[k], def[m], m)) return false;
          if(struct[k].content) compareStructure(struct[k].content, def[m]);
        }
      }
    }
  }
}

function verifyThis(struct, def, prop){
  // This is where the checks for types and values are made.
}

比较函数仍在进行中,但这就是我现在要使用的概念。

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.

var structure = {
  property1: {id:"name", type:"string", required:false},
  property2: {
    id:"categories", type:"object", required:true,
    content:{
      property1:{
        type:"object", min:1,
        content:{
          property1:{id:"depth", type:"positiveinteger", required:false},
          property2:{
            id:"groups", type:"object", required:true,
            content:{
              property1:{
                type:"array", min:1,
                content:{
                  type:"object", min:1,
                  content:{
                    property1:{id:"myFunction", type:"function", required:true},
                    property2:{id:"args", type:"array", required:false},
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Then I run a function that compares the blueprint ("struct") with the object to be tested ("def"):

function compareStructure(struct, def){
  if(isArray(def)){
    if(isDefined(struct.min) && def.length < struct.min){ alert("Error in structur check: " + " min is " + struct.min + "."); return false}
    if(isDefined(struct.max) && def.length > struct.max){ alert("Error in structur check: " + " max is " + struct.max + "."); return false}
    for(var i = 0; i < def.length; i++){
      compareStructure(struct.content, def[i]);
    }
  } else {
    for(var k in struct){
      if(struct[k].id){
        propFound = false;
        for(var m in def) if(m == struct[k].id) propFound = m;
        if(!propFound && struct[k].required){ alert("Error in structure check:  " + struct[k].id + " not defined."); return false}
        if(propFound && !verifyThis(struct[k], def[propFound], propFound)) return false;
        if(propFound && struct[k].content) compareStructure(struct[k].content, def[propFound]);
      } else {
        for(var m in def){
          if(!verifyThis(struct[k], def[m], m)) return false;
          if(struct[k].content) compareStructure(struct[k].content, def[m]);
        }
      }
    }
  }
}

function verifyThis(struct, def, prop){
  // This is where the checks for types and values are made.
}

The comparison function is still work in progress, but that's the concept I'm going with for now.

热血少△年 2024-11-14 13:34:10

您可以尝试根据 JSON 架构

但这可能有点过分了。

You can try to validate your object against a JSON Schema

But this may be an overkill.

鹤舞 2024-11-14 13:34:10

您可能会尝试 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文