【问题标题】:Adding up values of nested objects添加嵌套对象的值
【发布时间】:2016-06-03 13:34:07
【问题描述】:

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

对象:

$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);
          }

        })
      });
    };

我现在遇到的问题是将每个对象的所有totalWidth 和totalHeight 值相加,以获得所有墙壁组合的最终宽度和高度。必须有比下面更好的方法。

例如:

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

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您的功能可以稍微优化一下,我将假设您当前在哪里获得了 wall.wallWidth = 和 wall.wallHeight =,因为之前的属性不存在于您的示例数据,并且可能会引发错误。

    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/Height 属性,并在totalWidths 和totalHeights 变量中保持所有宽度和高度的总和。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2021-04-30
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      相关资源
      最近更新 更多