我尝试过对以“order”为键的javascript数组进行排序,但它只对父数组进行排序,而内部对象不进行排序
下面是我的示例代码,
JSON响应示例:
var MainObj = [
{
"title": "Merchant2",
"order": 2,
"subMenu": [
{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
},
{
"title": "Merchant1",
"order": 1,
"subMenu": [
{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
}
]
下面是排序功能,
var MainObj = [{
"title": "Merchant2",
"order": 2,
"subMenu": [{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
},
{
"title": "Merchant1",
"order": 1,
"subMenu": [{
"subMenu1": "Initiate2",
"order": 2
},
{
"subMenu2": "Initiate1",
"order": 1
}
]
}
]
var sort = function(prop, arr) {
prop = prop.split('.');
var len = prop.length;
arr.sort(function(a, b) {
var i = 0;
while (i < len) {
a = a[prop[i]];
b = b[prop[i]];
i++;
}
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return arr;
};
console.log(sort('order', MainObj));
但是预期的输出应该是下面的方式,
[
{
"title": "Merchant",
"order": 1,
"subMenu": [
{
"subMenu1": "Initiate1",
"order": 1
},
{
"subMenu1": "Initiate2",
"order": 2
},
]
}
]
2条答案
按热度按时间toiithl61#
在
sort
函数中,我们根本没有触及subMenu
,也不清楚为什么要拆分prop
,以及长度与任何内容有什么关系,但是基于示例输入和预期输出,它可以简单得多:vlurs2pr2#
根据
order
属性按升序对数组的内部对象进行排序。试试这个
输出:-