如何通过对象验证属性?我在 checkProperty
我希望 missingFields
返回 Batch.Name
is missing.
目前正在输出 [ '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);
最佳答案
在按点拆分后,您必须使用类似 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);
关于javascript - 通过对象验证属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801522/