簡體   English   中英

基於字符串值的對象的破折號排序數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM