使用通配符比较nodeJS对象

时间:2016-03-30 11:46:14

标签: javascript node.js

我正在寻找一种以更灵活的方式比较两个对象的方法。 我想要这样的东西:

var alice = {
                firstname:'Jan',
                lastname:'Smith',
                amount: 0,
                friendList:[], 
                removeAmount : function(amount){
                    this.amount = this.amount - amount;
                }
    };

应与此匹配

var aliceWildCard = {
            firstname: 'Jan',
            lastname:*,
            *,
            removeAmount : function(amount){
                this.amount = this.amount - amount;
            }
};

属性之后的*表示属性必须存在但值不重要。 请注意,“lastname:*”之后的*表示我允许声明其他属性。

是否存在允许我这样做的模块?我试图谷歌它但我找不到任何有用的东西。

1 个答案:

答案 0 :(得分:1)

我能想到的最接近的事情是使用一些JSON模式来再次验证你的对象。你可以使用像schema-validator

这样的几个nodejs模块来完成它

以下是有关如何使用schema-validator实现该示例的示例(请注意,这不是您想要的所有功能,但我相信您可以想到某些内容):

var Validator = require('schema-validator');

var aliceSchema = {
    type: Object,

    firstname: {
        type: String,
        required: true,
        test: /^Jan$/i
    },

    lastname: {
        type: String,
        required: true
    },

    removeAmount: {
        type: Function,
        required: true
    }
}


var aliceValidator = new Validator(aliceSchema);
aliceValidator.debug = true;

var result = aliceValidator.check({
    firstname: 'Jan',
    lastname: 'Smith',
    removeAmount: function() { }
});

console.log(result);

你的代码片段的问题在于你的aliceWildcard对象甚至不能被Javascript解析,因为那是通配符表示法。您可能需要搜索另一种方法来验证对象的内容(如schema-validator)。

相关问题