var data = {
chart : 'rank',
labels: [
{
0: 'First Choice'
1: 'Second Choice',
2: 'Third Choice',
3: 'Fourth Choice',
4: 'Fifth Choice'
}
],
rows: [
{
0: 2,
1: 8,
2: 1,
3: 30
4: 4
}
]
}
有没有办法重新排序结果,以便将行重新排序为从最高到最低,相应的标签也会重新排序,如下所示:
var data = {
chart : 'rank',
labels: [
{
0: 'Fourth Choice'
1: 'Second Choice',
2: 'Fifth Choice',
3: 'First Choice',
4: 'Third Choice'
}
],
rows: [
{
0: 30,
1: 8,
2: 4,
3: 2
4: 1
}
]
}
到目前为止,我已经设法使用以下内容对行数组进行了重新排序,但在标签方面却停滞不前了?
rows = rows.sort(function(a, b){return b-a});
答案 0 :(得分:2)
将对象值放入数组并对其进行排序。排序后根据排序数组更新真实对象。
var data = {
chart: 'rank',
labels: [{
0: 'First Choice',
1: 'Second Choice',
2: 'Third Choice',
3: 'Fourth Choice',
4: 'Fifth Choice'
}],
rows: [{
0: 2,
1: 8,
2: 1,
3: 30,
4: 4
}]
};
// get object property name array
Object.keys(data.labels[0])
// generate array with object values
.map(function(k) {
return [data.labels[0][k], data.rows[0][k]]
// sort the array based on rows value in array
}).sort(function(a, b) {
return b[1] - a[1];
// iterate and update real object
}).forEach(function(v, i) {
data.labels[0][i] = v[0];
data.rows[0][i] = v[1];
});
console.log(data);