2016-07-26 242 views
1
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

排序方法不能與對象 –

+0

使用的@PranavCBalan我已經parseJSON(數據)之後的陣列中使用排序; – ShambalaG

+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);