我有一个 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 :(得分: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 强>