How do I validate the property through object? I have define the list of Property in the checkProperty
I expected missingFields to return Batch.Name is missing.
Currently is is outputting [ 'Batch.Id', 'Batch.Name' ] which is wrong.
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);
You'll have to use something like reduce after splitting on dots to check whether the nested value exists:
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);
You can use this
The reason why thisdata[field]when dodata[Batch.Id]it tries to check at the first level key of object. in our case we don't have any key such asBatch.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With