0

Is there a way of order a key- value map like this:

<tr data-ng-repeat="(key, value) in vm.carryForwardInformation" data-ng-show="value.value != null && value.value != '00:00'">
            <td><b>{{key | translate}}</b>:</td>
            <td>{{value.value}}</td>
            <td>{{value.startDate}}</td>
            <td>{{value.endDate}}</td>
            <td>{{value.date}}</td>
        </tr>

I have tried the following but it didn't work:

data-ng-repeat="(key, value) in vm.carryForwardInformation | orderBy:key"
quma
  • 5,233
  • 26
  • 80
  • 146
  • 1
    Possible duplicate of [Order by Object key in ng-repeat](http://stackoverflow.com/questions/26474920/order-by-object-key-in-ng-repeat) – corn3lius Mar 21 '17 at 14:43

2 Answers2

1

You cannot use orderBy filter over an object. It only works over an array. So basically you have two options:

1. Order your object by key inside the controller and iterate over that sorted object (PLUNKER)

CONTROLLLER

var objectUnsorted = {
    "key2":{"id":2,"name":"Lisa","date":"11/11/2016"},
    "key3":{"id":3,"name":"Alice","date":"06/03/2017"},
    "key1": {"id":1,"name":"Christina","date":"17/05/2016"}
};

vm.sortedObject = orderByKey(objectUnsorted);

function orderByKey(data){
    let ordered = {};
    Object.keys(data).sort().forEach(function(key) {
      ordered[key] = data[key];
    });

    return ordered;
}

HTML

<tr ng-repeat="(key, value) in vm.soretdObject">

2. Convert your object to an array and user orderBy filter (PLUNKER)

CONTROLLER

var objectUnsorted = {
    "key2": {"id":2,"name":"Lisa","date":"11/11/2016"},
    "key3": {"id":3,"name":"Alice","date":"06/03/2017"},
    "key1": {"id":1,"name":"Christina","date":"17/05/2016"}
};

vm.dataArray = Object.keys(objectUnsorted).map(function (key) { 
    var obj = objectUnsorted[key];
    obj.key = key;

    return obj; 
});

HTML

<tr ng-repeat="data in vm.dataArray | orderBy:'key'">


** A third option could be do it with a filter (CHECK THIS ANSWER). But I don't believe that is a good approach convert to array in every digest cycle with a filter.
Community
  • 1
  • 1
The.Bear
  • 5,621
  • 2
  • 27
  • 33
0

orderBy looks for the properties you tell it to, within the current element from your array.

You should use the following syntax

orderBy: 'key'

Check this plunkr https://plnkr.co/edit/?p=preview

Pramod_Para
  • 671
  • 3
  • 10