我在Angular JS中创建一个站点的一部分,显示来自服务器的一些报告数据。由于我在表格中显示它,我需要的格式可以很容易地用ng-repeat显示。
因此,我需要将服务器中的JSON数据转换为JavaScript对象。我已经获得了我想要的数据的目标格式,这个对象使用了“捐赠程序”的名称。作为键,作为它们的值,每个对应一个月的对象数组。每个对象都有月份名称,在网站上注册的人数,捐赠人数以及捐赠总额。
我很难通过JSON迭代并将其转换为该格式。有人可以看看吗?我已经包含了我获得的服务器数据以及我尝试格式化它的方式。感谢。
服务器数据:
$scope.serverData = {
"registration_by_month": [
{
"month": "November 2015",
"registration_program": "Donor Program 1",
"count": 3
},
{
"month": "November 2015",
"registration_program": "Donor Program 2",
"count": 4
},
{
"month": "December 2015",
"registration_program": "Donor Program 1",
"count": 5
},
{
"month": "December 2015",
"registration_program": "Donor Program 2",
"count": 6
}
],
"donors_by_month": [
{
"month": "November 2015",
"registration_program": "Donor Program 1",
"count": 2
},
{
"month": "November 2015",
"registration_program": "Donor Program 2",
"count": 1
},
{
"month": "December 2015",
"registration_program": "Donor Program 1",
"count": 2
},
{
"month": "December 2015",
"registration_program": "Donor Program 2",
"count": 1
}
],
"donated_amount_by_month": [
{
"month": "November 2015",
"registration_program": "Donor Program 1",
"amount": 100
},
{
"month": "November 2015",
"registration_program": "Donor Program 2",
"amount": 200
},
{
"month": "December 2015",
"registration_program": "Donor Program 1",
"amount": 50
},
{
"month": "December 2015",
"registration_program": "Donor Program 2",
"amount": 40
}
]
};
目标数据:
$scope.targetData = {
"Donor Program 1": [{month:"November 2015", registered:3, donors:2, donated_amount:100},{month:"December 2015", registered:4, donors:1, donated_amount:200}],
"Donor Program 2:": [{month:"November 2015", registered:5, donors:2, donated_amount:50},{month:"December 2015",registered:6, donors:1, donated_amount:40}]
};
答案 0 :(得分:4)
试试这个
var temp = {};
data.registration_by_month.forEach(function (x) {
if (!temp[x.registration_program]) {
temp[x.registration_program] = [];
}
var dtmon = data.donors_by_month.find(function (y) {
return y.registration_program == x.registration_program;
});
var dnmon = data.donated_amount_by_month.find(function (y) {
return y.registration_program == x.registration_program;
});
temp[x.registration_program].push({
month: x.month,
registered: x.count,
donors: dtmon ? dtmon.count : 0,
donated_amount: dnmon ? dnmon.amount : 0
});
});
console.log(temp);
<强> JSFIDDLE 强>
编辑
IE和Opera不支持您可以尝试 .filter
喜欢这个
var temp = {};
data.registration_by_month.forEach(function (x) {
if (!temp[x.registration_program]) {
temp[x.registration_program] = [];
}
var dtmon = data.donors_by_month.filter(function (y) {
return y.registration_program == x.registration_program;
});
var dnmon = data.donated_amount_by_month.filter(function (y) {
return y.registration_program == x.registration_program;
});
temp[x.registration_program].push({
month: x.month,
registered: x.count,
donors: dtmon.length > 0 ? dtmon[0].count : 0,
donated_amount: dnmon.length > 0 ? dnmon[0].amount : 0
});
});
<强> JSFIDDLE 强>