使用Typescript按值排序对象数组

时间:2018-01-10 20:21:34

标签: javascript typescript

如何按对象值输出这个对象数组?我正在使用Typescript

的console.log(this.items);

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
{id: 3, ref: "P-201721", active: 1, visible: 1, weigth: 0.3, …}
{id: 4, ref: "P-201722", active: 1, visible: 1, weigth: 0.3, …}
{id: 1, ref: "P-201710", active: 1, visible: 1, weigth: 0.5, …}
{id: 2, ref: "P-201711", active: 1, visible: 1, weigth: 0.5, …}
{id: 5, ref: "P-201831", active: 1, visible: 1, weigth: 0.2, …}
{id: 6, ref: "P-201832", active: 1, visible: 1, weigth: 0.2, …}

我尝试了这个,但阵列保持相同的顺序 Sort an array with arrays in it by string

2 个答案:

答案 0 :(得分:5)

对对象数组进行排序可能有点棘手。您必须传递自定义排序功能以定义比较对象的方式。怎么会.sort()知道你想按ID排序?也许你想按重量排序。

我在https://codepen.io/anon/pen/PEReGE?editors=0012汇总了一个例子。如果您希望将id引用替换为任何属性,则可以将其替换为。

items.sort((a, b) => {
  if(a.id > b.id) {
    return 1;
  } else if(a.id < b.id) {
    return -1;
  } else {
    return 0;
  }
});

如果您按数字属性排序,可以使用此简写:

items.sort((a, b) => {
  return a.id - b.id;
});

答案 1 :(得分:2)

您可以使用lodash来实现您想要的效果。您还可以通过传入sortBy函数内的数组中的键来使用多个排序选项。

&#13;
&#13;
var data = [
{"id": 3, "ref": "P-201721", "active": 1, "visible": 1, "weight": 0.3},
{"id": 4, "ref": "P-201722", "active": 1, "visible": 1, "weight": 0.3},
{"id": 1, "ref": "P-201710", "active": 1, "visible": 1, "weight": 0.5},
{"id": 2, "ref": "P-201711", "active": 1, "visible": 1, "weight": 0.5},
{"id": 5, "ref": "P-201831", "active": 1, "visible": 1, "weight": 0.2},
{"id": 6, "ref": "P-201832", "active": 1, "visible": 1, "weight": 0.2}
]

var sort = _.sortBy(data, ["id","weight"]);

console.log(sort);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;