gpt4 book ai didi

javascript - Lo-dash 根据字符串值对对象数组进行排序

转载 作者:行者123 更新时间:2023-11-30 16:08:40 27 4
gpt4 key购买 nike

假设我有一个像这样的对象数组

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 ,但这并不是我想要的,因为在我的例子中,顺序将是固定的,并且排序不会基于随机字符串值。

最佳答案

试试这个

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;
});
});

另一种方法,我想是更简洁的方法(感谢 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;
});
});

关于javascript - Lo-dash 根据字符串值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615012/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com