Check if object value exists and set new value for object key | Code optimization
Recently I have seen a code in the production that is
if (!angular.isUndefined(newVal)) { if(!angular.isUndefined(newVal.min)){ $scope.dataPoints.min = newVal.min; } if(!angular.isUndefined(newVal.max)){ $scope.dataPoints.max = newVal.max; } if(!angular.isUndefined(newVal.yellowRangeMin)){ $scope.dataPoints.yellowRangeMin = newVal.yellowRangeMin; } if(!angular.isUndefined(newVal.yellowRangeMax)){ $scope.dataPoints.yellowRangeMax = newVal.yellowRangeMax; } if(!angular.isUndefined(newVal.redRangeMin)){ $scope.dataPoints.redRangeMin = newVal.redRangeMin; } if(!angular.isUndefined(newVal.redRangeMax)){ $scope.dataPoints.redRangeMax = newVal.redRangeMax; } }It could be optimized through loop as
if (!angular.isUndefined(newVal)) { var props = ['min','max','yellowRangeMin','yellowRangeMax','redRangeMin','redRangeMax']; _.each(props, function (prop) { if(!angular.isUndefined(newVal[prop])){ $scope.dataPoints[prop] = newVal[prop]; } }); }