【问题标题】:Select names to array from object从对象中选择要排列的名称
【发布时间】:2015-08-10 08:32:28
【问题描述】:

我有这个领域的课程:

 public class TimesheetModel
    {
        public DateTime TaskDate { get; set; }
        public List<TimesheetListModel> TimesheetList { get; set; }

        public TimesheetModel() { TimesheetList = new List<TimesheetListModel>(); }
    }

列表有这样的结构:

public class TimesheetListModel
    {
        public string ProjectName { get; set; }
        public DateTime TaskDate { get; set; }
        public string Task { get; set; }
        public decimal TimeWorked { get; set; }
        public string Note { get; set; }
    }

当我加载我的页面 TimesheetModel 从数据库获取数据时,它可以正常工作,我可以通过页面上的 angularjs 查看数据。 但我还需要选择 ProjectNames 来排列没有重复项,因为 TimesheetListModel 列表有 ProjectName 的重复项。 我用这样的代码写这个:

    $scope.bindModel = function(data) {
         $scope.model = data;
         $scope.projects = function () {
            var array = [];
            array.push($scope.model[0].TimesheetList[0].ProjectName);
            for (var i = 0; i < $scope.model.length; i++) {
                for (var j = 0; j < $scope.model.TimesheetList.length; j++) {
                            if ($scope.model[i].TimesheetList[j].ProjectName != array[i - 1]) {
                                array.push($scope.model[i].TimesheetList[j].ProjectName);
                            }
                        }
                    }
                    return array;
                };
    };

我认为我犯了错误,因为我的 javascript 知识不好。请帮我解决这个问题。

【问题讨论】:

  • 你的 var model 是什么?不是$scope.model吗?
  • @Pierre-Alexandre Moller,我重写代码
  • 还是同样的问题?
  • @Pierre-Alexandre Moller,在控制台显示错误:无法读取 $scope.model.TimesheetList.lenght 中未定义的属性“长度”
  • 在你的第二个for 你的$scope.model 可能需要像$scope.model[i].TimesheetList.length 这样的索引。

标签: javascript asp.net angularjs


【解决方案1】:

我修改了代码,其中包含检查重复的arrayContains函数

   $scope.bindModel = function(data) {
      $scope.model = data;
      var arrayContains = function(arr, value) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] === value) {
            return true;
          }
        }
      }
      $scope.projects = function() {
        var array = [];
        for (var i = 0; i < $scope.model.length; i++) {
          for (var j = 0; j < $scope.model.TimesheetList.length; j++) {
            if (!arrayContains(array, $scope.model[i].TimesheetList[j].ProjectName)) {
              array.push($scope.model[i].TimesheetList[j].ProjectName);
            }
          }
        }
        return array;
      };
    };

您可以使用具有实用功能的jQuery来代替编写代码:

$.inArray(value, arr)

【讨论】:

  • 用此代码“for (var j = 0; j
猜你喜欢
  • 2018-01-28
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 2017-01-06
  • 1970-01-01
  • 2016-08-18
相关资源
最近更新 更多