我正在寻找一种以更灵活的方式比较两个对象的方法。 我想要这样的东西:
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:*”后面的 * 表示我允许声明其他属性。
是否存在允许我执行此操作的模块?我尝试用谷歌搜索,但找不到任何有用的东西。
最佳答案
我能想到的最接近的事情是使用一些 JSON 模式来再次验证您的对象。您可以使用几个 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 解析。您可能需要寻找另一种方法来验证对象的内容(例如架构验证器)。
关于javascript - 使用通配符比较nodeJS对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307868/