繁体   English   中英

在给定的对象数组中搜索键并替换值;

[英]Search for the key in the given array of objects and replace the value;

实现多种排序功能; 在哪里需要切换包含排序字段名称和排序顺序的数组;

单击按名称排序:

[{"sortKey":"name","sortValue":"desc"}]

再次单击“按名称排序”:

[{"sortKey":"name","sortValue":"asc"}]

点击按年龄排序:

[{"sortKey":"name","sortValue":"asc"},{"sortKey":"age","sortValue":"desc"} ]

再次单击“按名称排序”:

[{"sortKey":"name","sortValue":"desc"},{"sortKey":"age","sortValue":"desc"} ]

DEMO

if (checkIfObjectExists($scope.sortList, sortingObject)) {
    if (!$scope.sortList.hasOwnProperty(sortingObject.sortType)) {
        console.log($scope.sortList);
        // replace the value for the key
    }
} else {
    $scope.sortList.push(sortingObject);
}

我在您的实现中更改了一些内容。 问题是您要检查整个对象是否不相同,然后将其推入数组。 但是,如果sorKey相同,则需要反转sortValue

DEMO

将您的函数checkIfObjectExists更改为updateArray

function updateArray(array, newObject) {
    var i = 0;
    for (i = 0; i < array.length; i++) {
      var object = array[i];
      if (object.sortKey == newObject.sortKey) {
        object.sortValue= (object.sortValue==='asc')?'desc':'asc';
        return;
      }
    }
    array.push(newObject);
  }

在打电话时,我只会在$scope.clickMe这样$scope.clickMe

updateArray($scope.sortList, sortingObject);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM