2015-11-07 217 views
1

我有一個解決方案,但我不太滿意實現。通過子對象屬性值排序對象屬性

想在這裏得到一些反饋意見,說明如何改進這一點,無論是排序還是數據結構。

我想要做的是按其子對象屬性值中的一個對象的屬性進行排序。

我的數據結構如下:

對象調用冠軍:

{ '32': { played: 1, image: 'Amumu.png', won: 0 }, 
    '60': { played: 5, image: 'Elise.png', won: 3 }, 
    '79': { played: 4, image: 'Gragas.png', won: 3 }, 
    '245': { played: 1, image: 'Ekko.png', won: 0 }, 
    '254': { played: 2, image: 'Vi.png', won: 1 }, 
    '421': { played: 2, image: 'RekSai.png', won: 0 }, 
    // order is an array where I pushed all the objects image values 
    order: 
    [ 'Amumu.png', 
    'Elise.png', 
    'RekSai.png', 
    'Ekko.png', 
    'Gragas.png', 
    'Vi.png' ] 
} 

現在我想創造出由圖像名稱的字母順序排序對象排序順序。

這是我正在做的那一刻:

champions.order.sort(); // sorts the order array alphabetically 
// loops to replace the strings of the order array with the 
// corresponding parent object keys 
for(var j =0; j < champions.order.length; j++){ 
    for(var k in champions){ 
     if(k != "order"){ 
      if(champions.order[j] === champions[k].image){ 
       champions.order[j] = k; 
      } 
     } 
    } 
}; 

這給了我希望的結果爲對象的順序屬性:

{ '32': { played: 1, image: 'Amumu.png', won: 0 }, 
    '60': { played: 5, image: 'Elise.png', won: 3 }, 
    '79': { played: 4, image: 'Gragas.png', won: 3 }, 
    '245': { played: 1, image: 'Ekko.png', won: 0 }, 
    '254': { played: 2, image: 'Vi.png', won: 1 }, 
    '421': { played: 2, image: 'RekSai.png', won: 0 }, 
    order: [ '32', '245', '60', '79', '421', '254' ] } 

任何想法,如果可以做到這一點更容易?或者與另一個數據結構?

回答

1

嘗試使用Object.keys()

​​
+0

這種的考慮到了'order'財產,這似乎是OP想要的東西給定的順序? – 2015-12-20 05:50:52

+0

@torazaburo plnkr http://plnkr.co/edit/g6bYSz186tui8MtbhPhq?p=info – guest271314