让我们说我有一个像这样的对象数组
var outer = [
{
"name": "T1",
"inner": [
{
"type": "DAY"
},
{
"type": "MONTH"
},
{
"type": "WEEKLY"
}
]
},
{
"name": "T2",
"inner": [
{
"type": "DAY"
},
{
"type": "MONTH"
},
{
"type": "WEEKLY"
}
]
}
];
我基本上试图对内部数组中的对象进行排序,以便'类型'按此顺序 - 每月,每周,每天。像这样。
"inner": [
{
"type": "MONTH"
},
{
"type": "WEEKLY"
},
{
"type": "DAY"
}
]
有没有办法使用Lo-dash来做到这一点?这是一个small fiddle。
我看到了similar question here,但这并不是我想要的,因为在我的情况下,订单将被修复,而排序将不会基于随机字符串值。
答案 0 :(得分:2)
试试这个
var priority = [ "MONTH", "WEEKLY", "DAY" ];
outer.forEach(function(obj){
obj.inner.sort(function(a,b){
var ap = priority.indexOf(a.type);
var bp = priority.indexOf(b.type);
return ap-bp;
});
});
替代approcah,我想更清洁的方法(感谢 T.J.Crowder :))
var priority = {MONTH: 0, WEEKLY: 1, DAY: 2};
outer.forEach(function(obj){
obj.inner.sort(function(a,b){
var ap = priority[a.type];
var bp = priority[b.type];
return ap-bp;
});
});