Adding Up Values Of Nested Objects
I have an object which contains multiple objects. Each object has a height and a width, which I need to add together to get a total height and width. I need to update the totals
Solution 1:
Your function can be optimised a little and I'm going to assume where you've currently got wall.wallWidth = and wall.wallHeight = you meant to have wall.totalWidth = and wall.totalHeight = as the previous properties don't exist in your example data and will have likely thrown an error.
var totalWidths = 0,
totalHeights = 0;
$scope.setTotalWidthAndHeight = function()
{
angular.forEach($scope.walls, function(wall)
{
wall.totalWidth = wall.wFeet + (0.0833 * wall.wInches);
wall.totalHeight = wall.hFeet + (0.0833 * wall.hInches);
totalWidths += wall.totalWidth;
totalHeights += wall.totalHeight;
});
};
I've altered your function to do all the totalling in one swoop. It will populate the totalWidth/Height properties of your initial object and also keep a running total of all widths and heights in the totalWidths and totalHeights variables.
Post a Comment for "Adding Up Values Of Nested Objects"