按照子对象属性值sorting对象属性

我有一个解决scheme,但我不是很满意的实施。

希望在这里得到一些反馈,如何改进,无论是sorting或数据结构。

我想要做的是通过其一个子对象属性值为对象的属性sorting。

我的数据结构如下:

对象叫冠军:

{ '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' ] } 

现在我想创build一个sorting顺序,按照图像名称的字母顺序sorting对象。

这是我现在这样做的:

 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' ] } 

任何想法,如果这可以实现更容易? 或者与另一个数据结构?

尝试使用Object.keys()

  var res = Object.keys(champions).slice(0, -1).sort(function(a, b) { return champions[a].image.toLowerCase() > champions[b].image.toLowerCase() ? 1 : 0 })