Beslinda N.
Beslinda N.

Reputation: 5316

Ordering the objects in a particular order - Angular

I have an object of objects. And I want to show the objects and its values in specific order.(not alphabetically)

How can I achieve that with angular? Here it is my sample object

var filters = {
    language : { someProperty : "prop1", someOther : "prop2" },
    country : { resumeProp : "prop", resumeProp2 : false },
    destination { resumeProp : "prop", resumeProp2 : false },
};

I want to arrange example destination, country and then language.

Upvotes: 0

Views: 1358

Answers (1)

Jonathan Argentiero
Jonathan Argentiero

Reputation: 5727

JavaScript objects are unordered by definition (see the ECMAScript Language Specification, section 4.3.3). The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.

If you need things to be ordered, use an array and the Array.prototype.sort method:

var filters = [
    { name: "language", order: 2, someProperty : "prop1", someOther : "prop2" },
    { name: "country", order: 1, resumeProp : "prop", resumeProp2 : false },
    { name: "destination", order: 0, resumeProp : "prop", resumeProp2 : false }
];

function compare(a,b) {
  if (a.order < b.order)
    return -1;
  else if (a.order > b.order)
    return 1;
  else 
    return 0;
}

filters.sort(compare); // destination, country, language

If you are coding in ES6 you can use the Map object which is similar to an Object and guarantees key order.

If the original object cannot be modified then

  1. create another array with the object's indexes like var filtersKey = ['destination', 'country', 'language'];

  2. run the ng-repeat on that array.

  3. get the values from the original object using filters[value] where value represents each string contained in filtersKey exposed by the ng-repeat.

Upvotes: 1

Related Questions