[英]Iterating through an array and sum a value based on a condition in lo-dash
[英]Lo-dash sort array of objects based on string value
假設我有一個像這樣的對象數組
var outer = [
{
"name": "T1",
"inner": [
{
"type": "DAY"
},
{
"type": "MONTH"
},
{
"type": "WEEKLY"
}
]
},
{
"name": "T2",
"inner": [
{
"type": "DAY"
},
{
"type": "MONTH"
},
{
"type": "WEEKLY"
}
]
}
];
我基本上是想對內部數組中的對象進行排序,以使“類型”按此順序排列-MONTH,WEEKLY,DAY。 像這樣。
"inner": [
{
"type": "MONTH"
},
{
"type": "WEEKLY"
},
{
"type": "DAY"
}
]
有沒有辦法使用Lo-dash做到這一點? 這是一個小提琴 。
嘗試這個
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;
});
});
另一種替代方法,我猜想更清潔的方法(感謝TJ 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;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.