我是JSON的新手,我正在从服务器收到的响应中准备客户端的JSON对象。 我希望数据如下所示
[
{"number" : "456" ,
"effort" : [{
"effort_type" : "A",
"act_effort" : 10 },
{"effort_type" : "B",
"act_effort" : 20 }]
},
{"number" : "123" ,
"effort" : [{
"effort_type" : "A",
"act_effort" : 5},
{"effort_type" : "B",
"act_effort" : 30},
{"effort_type" : "C",
"act_effort" : 15}]
}
]
我正在从服务器收到的响应中创建此JSON,如下所示
$http.get('/colist').success(function(response) {
//console.log ("i GET the data of projects");
$scope.project = response;
}
下面是准备我的第二个json对象的代码
var actEffortData = [];
var dataSource = $scope.project;
for(i=0; i<dataSource.length; i++){
var dupCoFound="N";
var currentNumber=dataSource[i].number;
var currentEffort = parseInt(dataSource[i].act_effort);
var currentEffortType= dataSource[i].effort_type;
if(i==0){
actEffortData.push({
number : currentNumber,
effort : {
effort_type:currentEffortType,
act_effort:currentEffort
}
});
} else {
for(k=0; k < actEffortData.length; k++){
var dupCEffFound="N";
if(actEffortData[k].number == currentNumber){
for(n=0; n < actEffortData[0].effort.length; n++){
if(actEffortData[k].effort[n].effort_type == currentEffortType){
var currentEffortTemp = actEffortData[k].effort[n].act_effort + currentEffort;
actEffortData[k].effort[n].act_effort = currentEffortTemp;
dupCEffFound="Y";
break;
}
}
if(dupCEffFound == "N"){
var tempActEffort =[];
tempActEffort = actEffortData[k].effort;
tempActEffort.push({
effort_type:currentEffortType,
act_effort:currentEffort
});
}
dupCoFound = "Y";
break;
}
}
if (dupCoFound=="N"){
actEffortData.push({
number : currentNumber,
effort : {
effort_type:currentEffortType,
act_effort:currentEffort
}
});
}
}
我收到如下错误:
Error: tempActEffort.push is not a function
有人能告诉我如何实现这一目标吗? 请注意,实际代码的功能多于上述代码,因此您可能会发现冗余变量的使用情况。
提前致谢。
答案 0 :(得分:1)
我在你的代码中发现了一件事:
var tempActEffort =[];
tempActEffort = actEffortData[k].effort;
在这里,您将变量'tempActEffort'声明为数组。然后直接将某个值初始化为'tempActEffort = actEffortData [k] .effort',以便其类型从数组更改为结果类型。所以,push不是一个定义的函数,因为它现在不是一个数组类型。
因此,不要将值指定为'tempActEffort = actEffortData [k] .effort'而是将其更改为:
tempActEffort.push(actEffortData[k].effort);
答案 1 :(得分:0)
检查是否
tempActEffort = actEffortData[k].effort;
返回一个数组对象。推送只能应用于数组