我正在研究Angular7和Typescript, 我想在打字稿中对字典数组进行排序。 这是我的数据:
{
"data": [
{
"name": "Azad University",
"tedad": 80
},
{
"name": "University of Science and Technology",
"tedad": 14
},
{
"name": "University of Kurdistan",
"tedad": 30
}
]
}
我想用tedad
键对这些数据进行排序。我该怎么办?
我在stackoverflow上看到了这段代码,但我不知道如何更改它的工作原理:
items.sort(function(first, second) {
return second[1] - first[1];
});
答案 0 :(得分:0)
在ts文件中:
sample = {
"data": [
{
"name": "Azad University",
"tedad": 80
},
{
"name": "University of Science and Technology",
"tedad": 14
},
{
"name": "University of Kurdistan",
"tedad": 30
}
]
}
constructor(){
this.sample.data.sort(function(first, second) {
return (first.tedad - second.tedad);
});
console.log(this.sample);
}
答案 1 :(得分:0)
Array.prototype.sort()
中的参数是数组的元素。您可以按其财产进行访问。
const items = {
"data": [{
"name": "Azad University",
"tedad": 80
},
{
"name": "University of Science and Technology",
"tedad": 14
},
{
"name": "University of Kurdistan",
"tedad": 30
}
]
}
const sorted = items.data.sort((prev, curr) => prev.tedad - curr.tedad);
console.log(sorted)