2015-10-21 114 views
0

我有一個JSON對象的結構是這樣的:重組JSON對象

[ 
    {"CodeId": 1,"Description": "DESC1","Text": "TEXT 1 GB en","CodeCountry": "GB","CodeLanguage": "en"}, 
    {"CodeId": 1,"Description": "DESC1","Text": "TEXT 1 BE fr","CodeCountry": "BE","CodeLanguage": "fr"}, 
    {"CodeId": 1,"Description": "DESC1","Text": "TEXT 1 BE nl","CodeCountry": "BE","CodeLanguage": "nl"}, 
    {"CodeId": 2,"Description": "DESC2","Text": "TEXT 2 DE de","CodeCountry": "DE","CodeLanguage": "de"}, 
    {"CodeId": 2,"Description": "DESC2","Text": "TEXT 2 GB en","CodeCountry": "GB","CodeLanguage": "en"}, 
    {"CodeId": 2,"Description": "DESC2","Text": "TEXT 2 BE nl","CodeCountry": "BE","CodeLanguage": "nl"} 
] 

,我想它重組這樣的:

[ 
    { 
     "CodeId": 1, 
     "Description": "DESC1", 
     "languages": 
     [ 
      {"Text": "TEXT 1 GB en","CodeCountry": "GB","CodeLanguage": "en"}, 
      {"Text": "TEXT 1 BE fr","CodeCountry": "BE","CodeLanguage": "fr"}, 
      {"Text": "TEXT 1 BE nl","CodeCountry": "BE","CodeLanguage": "nl"}, 
     ] 
    }, 
    { 
     "CodeId": 2, 
     "Description": "DESC2", 
     "languages": 
     [ 
      {"Text": "TEXT 2 DE de","CodeCountry": "DE","CodeLanguage": "de"}, 
      {"Text": "TEXT 2 GB en","CodeCountry": "GB","CodeLanguage": "en"}, 
      {"Text": "TEXT 2 BE nl","CodeCountry": "BE","CodeLanguage": "nl"}, 
     ] 
    }, 

] 

有沒有人誰可以幫助?

其實我想填充table與使用AngularJS服務器數據,我沒有訪問到服務器,但我可以創建一個JS功能與數據玩。

我已經嘗試使用AngularJS中的過濾器來填充表格,但我正在使用分頁模塊,並且我嘗試使用這種方法時遇到問題。

我相信,我唯一的解決方案是創建一個JS函數改變JSON,但如果有人有其他的解決方案,我在這裏聽到的!

感謝;)

+0

在你的情況,分組將在代碼ID的基地完成,說明? –

+0

是的,每個CodeID的描述是唯一的,所以CodeID分組@AmitSoni – ben

+0

@charlietfl我已經提出了這樣的解決方案,但正如我所說我正在使用兩個不同的模塊'angularUtils.directives.dirPagination'和'angular.filter' 。有了這個解決方案,我有很多問題與分頁 – ben

回答

1

每當你需要做這樣的事情,你通常需要創建一個臨時的對象,它的鍵就可以方便地引用,以便能夠像項目組。

然後,一旦你分組循環通過溫度對象,以獲取最終結果

var tmp ={} 

data.forEach(function(item){ 
    // create the key for temp object that will be used for grouping 
    var tempKey = item.CodeId; 
    // OR if want to group by both CodeId and Description 
    var tempKey = item.CodeId + item.Description; 

    // create a new property if matching one doesn't exist already 
    if(!tmp.hasOwnProperty(tempKey)){ 
     tmp[tempKey] = { 
      "CodeId": item.CodeId, 
      "Description": item.Description, 
      "languages":[] // new nested array to push to 
     }; 
    } 
    // at this point there will always be a tmp[tempKey].languages array to push to 

    // manually create language object if you don't want the extra 
    // properties already set above, otherwise use whole item object 
    tmp[tempKey].languages.push(item); 

}); 
// map the temp object to a final results array 
var results = Object.keys(tmp).map(function(key){ 
    return tmp[key]; 
}); 

的語言對象將在您的數據充分對象。如果您不想在每個這些內容中添加其他屬性,則可以在推送到tmp[tempKey].languages之前手動創建一個新對象。爲了簡單起見,我離開了你

DEMO