我有以下2个整数数组以及拒绝的原因:
var approvedItems = [2051, 2567];
var deniedItems = [2053, 2569];
string deniedReason = "Naughty";
我想创建以下JSON:
{
"Responses": [{
"ResponseID": 2051,
"IsApprove": true
},
{
"ResponseID": 2567,
"IsApprove": true
},
{
"ResponseID": 2053,
"IsApprove": false
},
{
"ResponseID": 2569,
"IsApprove": false
}],
"Reason": "Naughty"
}
我怎么能用angular / javascript做到这一点?
答案 0 :(得分:3)
怎么样?
var approvedItems = [2051, 2567];
var deniedItems = [2053, 2569];
var deniedReason = "Naughty";
var result={
Responses:[],
"Reason":deniedReason
}
approvedItems.forEach(a =>{result.Responses.push({
"ResponseID": a,
"IsApprove": true
})})
deniedItems.forEach(d =>{result.Responses.push({
"ResponseID": d,
"IsApprove": false
})})
console.log(result);
答案 1 :(得分:1)
可以帮助
var approvedItems = [2051, 2567];
var deniedItems = [2053, 2569];
var deniedReason = "Naughty";
var resResponse = {};
var responses = [];
if(approvedItems.length || deniedItems.length) {
for(var ind =0; ind < approvedItems.length; ind++) {
var response = {
"ResponseID": approvedItems[ind],
"IsApprove": true
}
responses.push(response);
}
for(var ind =0; ind < deniedItems.length; ind++) {
var response = {
"ResponseID": deniedItems[ind],
"IsApprove": false
}
responses.push(response);
}
resResponse["Responses"] = responses;
}
if(deniedReason) {
resResponse["Reason"] = "deniedReason";
}