Patricio Vargas Patricio Vargas - 11 months ago 64
Javascript Question

Adding new properties to JSON with a forloop doesn't work

I'm trying to add new properties to an Array of JSON object dynamically using a for loop, but it's very weird that if I hardcode the index of the object instead of using i, it works.

This works:

sa.savannahWS.completedWorkOrder("09/29/2017").then(function(response) {
response.invocationResult.result[0].CSXPMTWO = "TEST";
response.invocationResult.result[1].CSXPMTWO = "TEST";
console.log(response.invocationResult.result);
}, function(error) {
sa.savannahUtils.showErrorPopup("Error In Creating Wiring House", error);
});


These doesn't work:

sa.savannahWS.completedWorkOrder("09/29/2017").then(function(response) {
console.log(response.invocationResult.result);
for(var i = 0; i<response.invocationResult.result.size; i++) {
response.invocationResult.result[i].CSXPMTWO = "TEST";
}
console.log(response.invocationResult.result);
}, function(error) {
sa.savannahUtils.showErrorPopup("Error In Creating Wiring House", error);
});





sa.savannahWS.completedWorkOrder("09/29/2017").then(function(response) {
console.log(response.invocationResult.result);
for(var i = 0; i<response.invocationResult.result.size; i++) {
response.invocationResult.result[i]["CSXPMTWO"] = "TEST";
}
console.log(response.invocationResult.result);
}, function(error) {
sa.savannahUtils.showErrorPopup("Error In Creating Wiring House", error);
});





sa.savannahWS.completedWorkOrder("09/29/2017").then(function(response) {
console.log(response.invocationResult.result);
for(var i = 0; i<response.invocationResult.result.size; i++) {
response.invocationResult.result[i].push({"CSXPMTWO": "TEST"});
}
console.log(response.invocationResult.result);
}, function(error) {
sa.savannahUtils.showErrorPopup("Error In Creating Wiring House", error);
});

Answer Source

Are you sure response.invocationResult.result.size is defined? Usually for arrays, the size of the array is .length

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download