我正在尝试对我的 javascript 对象数组进行排序
ownerName dogCode dogName
Bob 5 Rex
John
Alisha 3 Moon
Darren 4 Boss
Josh
Cerq
我希望它首先按dogCode排序(无论是否存在,忽略数字),然后按ownerName排序,最后按dogName排序,如下所示:
ownerName dogCode dogName
Alisha 3 Moon
Bob 5 Rex
Darren 4 Boss
Cerq
John
Josh
我试过这个:
data.sort(function (a, b) {
if (a.dogCode < b.dogCode || !a.dogCode) return 1;
if (a.dogCode > b.dogCode || !b.dogCode) return -1;
if (a.ownerName < b.ownerName || !a.ownerName) return 1;
if (a.ownerName > b.ownerName || !b.ownerName) return -1;
if (a.dogName < b.dogName || !a.dogName) return 1;
if (a.dogName > b.dogName || !b.dogName) return -1;
return 0;
});
显然,它是按dogCode 正确排序的,但不是按名称/dogName 排序的。我怎样才能做到这一点?
编辑:这是我的 json 对象:
{
"data": [
{
"ownerName": "Bob",
"dogCode": "5",
"dogName": "Rex"
},
{
"ownerName": "John"
},
{
"ownerName": "Alisha",
"dogCode": "3",
"dogName": "Moon"
},
{
"ownerName": "Darren",
"dogCode": "4",
"dogName": "Bos"
},
{
"ownerName": "Josh"
},
{
"ownerName": "Cerq"
}
]
}
慕勒3428872
哔哔one
相关分类