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' ] }
任何想法,如果可以做到这一点更容易?或者与另一个数据结构?
这种的考虑到了'order'财产,这似乎是OP想要的东西给定的顺序? – 2015-12-20 05:50:52
@torazaburo plnkr http://plnkr.co/edit/g6bYSz186tui8MtbhPhq?p=info – guest271314