2015-04-15 21 views
1

我的JSON樣式如下所示。總結出來之後,我正在尋找排序numberOfPoint的方法。如何對JSON中的總和數進行排序

{ "data": [ 
    { 
     "id": { 
      "year": 2015, 
      "Name": "A" 
     }, 
     "numberOfPoint": 2 
    }, 
    { 
     "id": { 
      "year": 2014, 
      "Name": "C" 
     }, 
     "numberOfPoint": 2 
    }, 
    { 
     "id": { 
      "year": 2014, 
      "Name": "B" 
     }, 
     "numberOfPoint": 2 
    }, 
    { 
     "id": { 
      "year": 2014, 
      "Name": "B" 
     }, 
     "numberOfPoint": 2 
    }, 
    { 
     "id": { 
      "year": 2013, 
      "Name": "C" 
     }, 
     "numberOfPoint": 2 
    }] 
} 

obj是我的JSON。

var result = {}; 

obj.data.forEach(function (a) { result[a["id"]["Name"]] = (result[a["id"]["Name"]] || 0) + a["numberOfPoint"]; }); 

結果是看起來像下面

{ 
    "A": 2, 
    "C": 4, 
    "B": 4 
} 

我怎樣才能解決這從最大到最小numberOfPoint? 我想要這樣的結果。

{ 
    "B": 4, 
    "C": 4, 
    "A": 2 
} 

在此先感謝您。

+3

你不能...一個對象的屬性不能排序..使用一個數組,而不是像'[{key:'B',總數:4},{鍵:'C',總數:4},{鍵:'A',總數:2}] –

+0

我該怎麼做數組? – user2210620

回答

1

您可以如下操作:

var result={ 
    "A": 2, 
    "C": 4, 
    "B": 4, 
    "D": 3 
}  

var temp = []; 
$.each(result, function(key, value) { 
    temp.push({v:value, k: key}); 
}); 
temp.sort(function(a,b){ 
    if(a.v < b.v){ return 1} 
    if(a.v > b.v){ return -1} 
     return 0; 
}); 

$.each(temp, function(index, obj) { 
    alert(obj.k + "-" + obj.v); 
}); 

Here is JSFiddle

1

也許這會有所幫助。

obj.data.sort(function(a, b) { 
    return a.id.Name < b.id.Name; 
}); 

for(var i in obj.data) { 
    console.log(obj.data[i].id.Name); 
} 
1
var obj = { "data": [ 
{ 
    "id": { 
     "year": 2015, 
     "Name": "A" 
    }, 
    "numberOfPoint": 2 
}, 
{ 
    "id": { 
     "year": 2014, 
     "Name": "C" 
    }, 
    "numberOfPoint": 2 
}, 
{ 
    "id": { 
     "year": 2014, 
     "Name": "B" 
    }, 
    "numberOfPoint": 2 
}, 
{ 
    "id": { 
     "year": 2014, 
     "Name": "B" 
    }, 
    "numberOfPoint": 2 
}, 
{ 
    "id": { 
     "year": 2013, 
     "Name": "C" 
    }, 
    "numberOfPoint": 2 
}] } 


var result = {}; 

obj.data.forEach(function (a) { 
    result[a["id"]["Name"]] = (result[a["id"]["Name"]] || 0) + a["numberOfPoint"]; 
}); 

var temp = []; 
$.each(result, function(key, value) { 
    temp.push({v:value, k: key}); 
}); temp.sort(function(a,b){ if(a.v < b.v){ return 1} 
if(a.v > b.v){ return -1} 
    return 0; }); 

$.each(temp, function(index, obj) { 
alert(obj.k + "-" + obj.v); }); 

我希望你喜歡this..if你喜歡,那麼請不要忘記投票給我..並感謝@Butani Vijay爲好分類。我已經實現了共同的...