如何通过对象验证属性?我在checkProperty
我期望missingFields
返回Batch.Name
丢失。
当前正在输出[ 'Batch.Id', 'Batch.Name' ]
,这是错误的。
let data = {
Batch: {
Id: 123,
},
Total: 100,
}
let checkProperty = ['Total', 'Batch.Id', 'Batch.Name'];
let missingFields = [];
checkProperty.forEach(field => {
if (!data[field]) {
missingFields.push(field);
}
});
console.log(missingFields);
答案 0 :(得分:3)
在点上分割后,您必须使用reduce
之类的东西来检查嵌套值是否存在:
let data = {
Batch: {
Id: 123,
},
Total: 100,
}
let checkProperty = ['Total', 'Batch.Id', 'Batch.Name'];
let missingFields = [];
checkProperty.forEach(field => {
const val = field.split('.').reduce((a, prop) => !a ? null : a[prop], data);
if (!val) {
missingFields.push(field);
}
});
console.log(missingFields);
答案 1 :(得分:1)
您可以使用此
The reason why this
数据[字段] when do
数据[Batch.Id] it tries to check at the first level key of object. in our case we don't have any key such as
Batch.Id .
For our case we need `data[Batch][Id]` something like this which first searches
for `Batch` property and than or the found value it searches for `Id`.
let data = {
Batch: {
Id: 123,
},
Total: 100,
}
let checkProperty = ['Total', 'Batch.Id', 'Batch.Name'];
let missingFields = [];
checkProperty.forEach(field => {
let temp = field.split('.').reduce((o,e)=> {
return o[e] || data[e]
},{});
if (!temp) {
missingFields.push(field);
}
});
console.log(missingFields);
答案 2 :(得分:0)
如果可以使用其他库,则Ajv非常适合。您可以创建一个架构并进行验证,而不必自己创建所有逻辑。
var schema = {
"type": "object",
"properties": {
"Batch": {
"type": "object",
"required": ["Id", "Name"],
"properties":
{
"Id":{},
"Name":{},
},
},
"Total": {}
}
};
let json = {
Batch: {
Id: 123,
},
Total: 100,
}
var ajv = new Ajv({
removeAdditional: 'all',
allErrors: true
});
var validate = ajv.compile(schema);
var result = validate(json);
console.log('Result: ', result);
console.log('Errors: ', validate.errors);
返回以下错误消息:
dataPath:".Batch"
keyword:"required"
message:"should have required property 'Name'"
params:{missingProperty: "Name"}
schemaPath:"#/properties/Batch/required"