[英]Sort json response of api alphabetically
I am trying to receive get api response in an alphabetically sorted order.我正在尝试按字母顺序接收 get api 响应。 I have tried the second answer from this question - Sort JSON response alphabetically using Javascript
我已经尝试了这个问题的第二个答案 - 使用 Javascript 按字母顺序排序 JSON 响应
My javascript code我的 javascript 代码
function OrderListBy(prop) {
return function (a, b) {
if (a[prop] > b[prop]) {
return 1;
}
if (a[prop] < b[prop]) {
return -1;
}
return 0;
};
}
router.get('/countries', async (req, res) => {
try {
const countries = await Country.find({}, 'name');
const sortedCountries = countries.sort(OrderListBy('name'));
res.send(sortedCountries);
} catch (e) {
res.status(500).send();
}
});
OUTPUT OUTPUT
[
{
"_id": "5f0ccf5f45a1a51ca99382a3",
"name": "Australia"
},
{
"_id": "5eb6c2e94298400b6eb6ca3c",
"name": "India"
},
{
"_id": "5ec68ca5325d997b752056cd",
"name": "china"
}
]
it should return China before India alphabetically.它应该按字母顺序在印度之前返回中国。 Its returning the countries in order they created.
它按照他们创建的顺序返回国家。 This isn't working.
这是行不通的。 What am I doing wrong?
我究竟做错了什么?
You can sort it in the query itself.您可以在查询本身中对其进行排序。 Try this
尝试这个
await Country.find({}, {'name': 1}).sort({name: 1})
Note: Inside sort, follow below values depending on result is required in which order.注意:在排序内部,根据需要的结果顺序遵循以下值。
1 Ascending
-1 Descending
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.