簡體   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