I am writing a validation method to make sure the required nested keys are present in data before calling another method that performs calculations using the data object. Here is the code thus far for the validation method -
function checkInputDataForMissingNestedKeys(data) {
const parentKeys = [
'initialDistance',
'finalDistance'
];
const nestedKeys = [
'value',
'uom'
];
let result = {};
// if parentKey exists in data, then check for nestedKeys
parentKeys.forEach(function(entry) {
if(data[entry] !== undefined) {
let i = 0;
nestedKeys.forEach(function(element) {
if(data[entry][element] === undefined) result[entry][i++] = element;
})
}
});
return (result.constructor === Object && Object.entries(result).length === 0) ? result : { "missing nested keys": result };
}
As written, an error is being encountered: "TypeError: undefined is not an object (evaluating 'result[entry][i++] = element')". I think it's broken due to result[entry][i++] = element; because when that part is changed to result[i++] = element; then the error goes away BUT overwriting of results occurs.
For testing purposes data['initialDistance'] and data['finalDistance] are both missing the nested key uom so the desired result of this, if outputted to the console (the formatting may not be flawless because it was written manually), is -
Object {
"missing nested keys": Object {
"initialDistance": Object {
"0": "uom"
},
"finalDistance": Object {
"0": "uom"
},
}
}
When result[i++] = element; is plugged in for experimentation then the console output looks like this (here again, typed out manually) -
Object {
"missing nested keys": Object {
"0": "uom"
}
}
What needs to be changed so that "missing nested keys" includes the values from entry?