我有以下数组,需要按国家/地区按字母顺序排序:
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}
但它仍然返回与原始数组相同的顺序。那么我如何使用国家作为基础对它进行排序?
使用sort
方法
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;}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句