按特定顺序对对象进行排序—Angular

Ordering the objects in a particular order - Angular

本文关键字:排序 Angular 对象 定顺序      更新时间:2023-09-26

我有一个对象的对象。我想以特定的顺序显示对象及其值。(不是按字母顺序)

我如何用angular实现这一点?这是我的样品对象

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

我想安排示例目的地,国家和语言。

JavaScript对象根据定义是无序的(请参阅ECMAScript语言规范,第4.3.3节)。语言规范甚至不能保证,如果您连续两次迭代对象的属性,它们第二次会以相同的顺序出现。

如果需要订购,请使用数组Array.prototype.sort方法:

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

如果您在ES6中进行编码,则可以使用Map对象,该对象类似于object并保证密钥顺序。

如果原始对象无法修改,则

  1. 使用对象的索引创建另一个数组,如var filtersKey = ['destination', 'country', 'language'];

  2. 在该数组上运行ng repeat

  3. 使用filters[value]从原始对象获取值,其中value表示ng repeat暴露的filtersKey中包含的每个字符串。