I have a function that checks two reference objects. They both have the same properties.
The purpose of this method is to ensure that any non-null old values are not overwritten with null or empty values after an API call. I'd appreciate any feedback.
evaluateEmptyValues: function(reference, originalReference) {
var vm = this;
// Get length
referenceLength = Object.entries(reference).length;
originalReferenceLength = Object.entries(originalReference).length;
// Evaluate both if they are the same length -- they always should be
if (referenceLength == originalReferenceLength) {
try {
for (var prop in reference) {
// First check for undefined or null
if (reference[prop] != undefined || reference[prop] != null) {
if (typeof (reference[prop]) == 'string' && reference[prop].trim() == '') {
// Assign original value to new object if new value is empty string
reference[prop] = originalReference[prop];
}
// Check if current prop in both objects is an object
if (typeof(reference[prop]) == 'object' && typeof(originalReference[prop]) == 'object') {
var length = Object.keys(reference[prop]).length;
// Do another loop
for (var property in reference[prop]) {
// Check for undefined or null value in original
if (originalReference[prop][property] != undefined) {
if (originalReference[prop][property] != null) {
if (reference[prop][property] == null || reference[prop][property] == '') {
// Assign old non-null value to new object if new value is empty or null
reference[prop][property] = originalReference[prop][property];
}
}
}
}
}
// Check for array
if (Array.isArray(reference[prop]) && typeof Array.isArray(originalReference[prop])) {
// Recurse if both are arrays
reference[prop].forEach((item, index) => vm.evaluateEmptyValues(item, originalReference[prop][index]));
}
} else {
if (originalReference[prop] != undefined) {
if (originalReference[prop] != null) {
// Assign original value to new object
reference[prop] = originalReference[prop];
}
}
}
}
} catch(err) {
console.log(err);
}
}
},
if (reference[prop] != undefined || reference[prop] != null) {is never false, making the last else redundant. If your code works then 9 lines can be removed without effect. Along with 4 lines of the try and catch, and the one linevar length = Object.keys(reference[prop]).length;lengthis never used, you have 12 out of 39 lines of code that does nothing. You should fix the code if you want a good review. \$\endgroup\$