我需要按嵌套的值对JSON数组进行排序。这是我正在使用的例程,它总是返回0
。我要排序的字段值为advancedoptions.storeId
。
orders.sort(GetSortOrder("advancedOptions.storeId"));
function GetSortOrder(prop) {
return function(a, b) {
if (a[prop] > b[prop]) {
return 1;
} else if (a[prop] < b[prop]) {
return -1;
}
return 0;
}
}
我想按storeId对JSON进行排序:
{
"orders": [
{
"orderId": 415354051,
"advancedOptions": {
"storeId": 376480
}
},
{
"orderId": 415172626,
"advancedOptions": {
"storeId": 375780
}
},
{
"orderId": 414286558,
"advancedOptions": {
"storeId": 376480
}
},
{
"orderId": 412403726,
"advancedOptions": {
"storeId": 376480
}
}
]
}
正确的排序顺序应为:
"orderId": 415172626,
"orderId": 415354051,
"orderId": 414286558,
"orderId": 412403726,
答案 0 :(得分:0)
这是您要传递的道具,您无法像a["advancedOptions.storeId"]
那样访问对象中的嵌套属性。您需要执行类似a["advancedOptions"]["storeId"]
的操作。您的函数始终返回0的原因是,a["advancedOptions.storeId"]
总是返回undefined
,不符合if语句。
答案 1 :(得分:0)
function GetSortOrder(select) {
return function(a, b) {
const propA = select(a);
const propB = select(b);
if (propA > propB) {
return 1;
} else if (propA < propB) {
return -1;
}
return 0;
};
}
const orders = [
{ advancedOptions: { storeId: 34 } },
{ advancedOptions: { storeId: 342 } },
{ advancedOptions: { storeId: 3 } },
];
orders.sort(GetSortOrder(function (i) { return i.advancedOptions.storeId }));
console.log(orders);
答案 2 :(得分:0)
如前所述,使用方括号符号object[property]
时不能访问嵌套属性。您需要为嵌套的每一层应用方括号,例如object[property][propery]
。调用a[advancedOptions.storeId]
时,它将返回undefined,因为使用方括号表示法访问storeId的正确语法是a[advancedOptions][storeId]
。
如果您只需要按一种属性排序,为什么不使用:
orders.sort((a, b) => a.advancedOptions.storeId > b.advancedOptions.storeId)
答案 3 :(得分:0)
请尝试按storeId
排序数据
ordersData.orders.sort((a,b) =>
a.advancedOptions.storeId < b.advancedOptions.storeId ? -1 : a.advancedOptions.storeId > b.advancedOptions.storeId ? 1 : 0
);
var ordersData = {
"orders": [
{
"orderId": 415354051,
"advancedOptions": {
"storeId": 376480
}
},
{
"orderId": 415172626,
"advancedOptions": {
"storeId": 375780
}
},
{
"orderId": 414286558,
"advancedOptions": {
"storeId": 376480
}
},
{
"orderId": 412403726,
"advancedOptions": {
"storeId": 376480
}
}
]
}
ordersData.orders.sort((a,b) =>
a.advancedOptions.storeId < b.advancedOptions.storeId ? -1 : a.advancedOptions.storeId > b.advancedOptions.storeId ? 1 : 0
);
console.log(ordersData);