在嵌套循环中推送到数组是重复最后一个值

时间:2016-08-26 06:44:30

标签: javascript arrays asynchronous

我正在尝试将元素推送到嵌套循环中的数组,但只有最后一个项目在最终数组中重复,我在哪里出错,javascript异步概念非常新.Below是我的函数将项目推送到数组。

$scope.showBeList = function(feed) {
  if (feed[srcServ.KEY_CONTENT_TEXT]) {
    var content = JSON.parse(feed[srcServ.KEY_CONTENT_TEXT])
    if (content) {
      $scope.beList = {};
      for (var key in content) {

        var decorationVal;
        //reading value from a lokijs collection
        var decoration = dataServ[srcServ.CONST_COLLECTION_DECORATION].find({
          'name': key
        });
        if (decoration && decoration.length) {
          decorationVal = decoration[0];
          if (decorationVal != null) {
            var tempObj = JSON.parse(decorationVal.value);
            if (tempObj) {
              var header = tempObj[key][key + '_HEADER'];
              if (header) {
                var counter = content[key].length;
                var tempItems = [];
                for (var j = 0; j < content[key].length; j++) {
                  (function(j) {
                    var obj = {};
                    obj[srcServ.KEY_MAIN_HEADER] = tempObj[key][srcServ.KEY_DESC];
                    obj[srcServ.KEY_SUB_HEADER] = header[srcServ.KEY_DESC];
                    obj.id = j;
                    var itemVal = content[key][j][key + '_HEADER'];
                    var details = [];
                    var notes = [];
                    for (var item in itemVal) {
                      var val = null;
                      var found = false;
                      for (var i = 0; i < header.field.length; i++) {
                        if (header.field[i].name == item) {
                          val = header.field[i];
                          found = true;
                          break;
                        }
                      }
                      if (found && val != null) {
                        val[srcServ.KEY_DESC_VALUE] = itemVal[item];
                        details.push(val);
                      }
                    }
                    obj.details = details;
                    counter--;
                    if (counter == 0) {
                      $scope.showMoreDetails = true;
                      $scope.beList.beItems = tempItems;
                      console.log(JSON.stringify($scope.beList));
                    }
                    tempItems.push(obj)
                  })(j);
                  // $scope.beList.beItems.push(obj);
                }
              }
            }
          }
        }
      }
    }
  }
}

0 个答案:

没有答案