添加嵌套对象的值

时间:2016-06-03 13:34:07

标签: javascript angularjs

我有一个包含多个对象的对象。每个对象都有一个高度和一个宽度,我需要将它们加在一起以获得总高度和宽度。我需要更新用户输入的总数。

对象:

$scope.myObj = {
  wall1: {
    wFeet: 0,
    wInches: 0,
    hFeet: 0,
    hInches: 0,
    totalWidth: 0,
    totalHeight: 0
  },
  wall2: {
    wFeet: 0,
    wInches: 0,
    hFeet: 0,
    hInches: 0,
    totalWidth: 0,
    totalHeight: 0
  },
  wall3: {
    wFeet: 0,
    wInches: 0,
    hFeet: 0,
    hInches: 0,
    totalWidth: 0,
    totalHeight: 0
  }
};

现在我有一个功能,它取脚和英寸值,转换为十进制英尺并将它们相加,以给出每个墙的总宽度和高度。

    $scope.setTotalWidthAndHeight = function() {
      angular.forEach($scope.walls, function(wall) {

        //first convert inches to decimal of ft
        angular.forEach(wall, function(dim, dimKey) {

          if(dimKey === 'wInches') {
            wall.wallWidth = wall.wFeet + (0.0833 * dim);
          }

          if(dimKey === 'hInches') {
            wall.wallHeight = wall.hFeet + (0.0833 * dim);
          }

        })
      });
    };

我现在遇到的问题是从每个对象中添加所有totalWidthtotalHeight值,以获得所有墙组合的最终宽度和高度。必须有一种比下面更好的方法。

例如:

var allTotalWidths = $scope.myObj.wall1.totalWidth + $scope.myObj.wall2.totalWidth + $scope.myObj.wall3.totalWidth;

1 个答案:

答案 0 :(得分:0)

您的功能可以稍微优化一下,我将假设您目前已经wall.wallWidth =wall.wallHeight =想要拥有wall.totalWidth =和{{{ 1}}因为先前的属性不存在于您的示例数据中,并且可能会抛出错误。

wall.totalHeight =

我改变了你的功能,一举完成所有的总计。它将填充初始对象的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; }); }; 属性,并保持totalWidth/HeighttotalWidths变量中所有宽度和高度的总计。

相关问题