查找数组

时间:2018-02-01 12:58:13

标签: javascript angularjs

我有一个由angularjs中的mysql表组成的数组,我用php将它返回到json并在angularjs中获取它。我已经创建了一个离子应用程序并使用angularjs。我可以删除项目,插入项目和编辑项目。项目具有属性优先级,我希望优先级是唯一的。所以在项目添加上我正在检查最后添加的item.priority,下一个具有优先级+ 1.在项目删除时,我检查item.priority,因此下一个添加的项目将优先级设置为已删除项目的优先级。但是例如我有6个项目并且我删除了item4所以下一个添加的项目将具有优先级4,但是当我添加下一个优先级5时,但是我已经有5个所以我想要优先级设置为7作为我有6件物品。所以我尝试的是:

$scope.priority = Math.max(parseInt($rootScope.obiadki.priority));

但它返回undefined。我的问题是,如何检查整个数组中所有对象的优先级属性的最大值。

我如何检索数据:

$scope.getData = function () {
    $http({
        method: 'get',
        url: 'mygetdatacodeurl'
    }).then(function successCallback(response) {
        // Store response data
        $rootScope.obiadki = response.data;
        $scope.checkPriority();
    });
};

我如何检查优先级:

$scope.checkPriority = function () {
   $scope.priority = Math.max(parseInt($rootScope.obiadki.priority));

};

我如何检查addItem的优先级:

$scope.checkPriorityOnAdd = function () {
    $scope.priority = parseInt($scope.priority) + 1;
};

我的addItem函数:

$scope.addItem = function() {
    $http({
        method: "post",
        url: 'myinsertcodeurl',
        data: {
            id: $scope.id,
            obiad_name: $scope.obiad_name,
            active: $scope.active,
            priority: $scope.priority
        },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
    $scope.getData();
    $scope.checkPriorityOnAdd();
};

我的deleteItem函数,我在delete上设置优先级:

$scope.onItemDelete = function(item) {
    $http({
        method: "post",
        url: 'mydeletecodeurl',
        data: {
            id: item.id
        },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
    $scope.getData();
    $scope.priority = item.priority;
};

2 个答案:

答案 0 :(得分:0)

您需要迭代对象数组中的所有元素,并将对象属性与初始化为0的最大值进行比较:

   $scope.max = 0 ;

    for (var i = 0; i <= $rootScope.obiadki.length; i++) {
    if ($rootScope.obiadki[i].priority>$scope.max) {
      $scope.max=$rootScope.obiadki[i].priority;
      this.returnObject = $rootScope.obiadki[i];      
     } 
  }

答案 1 :(得分:0)

使用Lambda

$scope.max = $rootScope.obiadki.reduce((prev, current) => (prev.priority > current.priority) ? prev : current);

使用功能也可以在旧浏览器中使用

$scope.max = $rootScope.obiadki.reduce(function(prev, current){return (prev.priority > current.priority) ? prev : current;});
相关问题