我有以下数组,需要按国家/地区的字母顺序排序:
data=[
{
"country": "China",
"brands": {
"abc": "123",
"def": "123",
},
"day": "2020-04-16",
"time": "2020-04-16T14:30:05+00:00"
},
{
"country": "Zimbawe",
"brands": {
"abc": "123",
"def": "123",
},
"day": "2020-04-16",
"time": "2020-04-16T14:30:05+00:00"
},
{
"country": "Africa",
"brands": {
"abc": "123",
"def": "123",
},
"day": "2020-04-16",
"time": "2020-04-16T14:30:05+00:00"
}
]
到目前为止我已经尝试过:
data.sort()
还有这个:
function(a, b){return a - b}
但它仍然返回与原始数组相同的顺序。那么如何以国家/地区为基础对此进行排序呢?
最佳答案
使用排序
方法
const data=[{"country": "China","brands": {"abc": "123","def": "123",},"day": "2020-04-16","time": "2020-04-16T14:30:05+00:00"},{"country": "Zimbawe","brands": {"abc": "123","def": "123",},"day": "2020-04-16","time": "2020-04-16T14:30:05+00:00"},{"country": "Africa","brands": {"abc": "123","def": "123",},"day": "2020-04-16","time": "2020-04-16T14:30:05+00:00"}];
data.sort((a, b) => a.country > b.country ? 1 : -1);
console.log(data);
.as-console-wrapper {min-height: 100% !important; top: 0;}
关于javascript - 使用 JavaScript 对对象进行排序和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61253342/