I'm doing the following code in javascript:
var res = [{}];
for (var idx = 0; idx < json.length; idx++) {
// if the environment is already entered in the result
if (res[idx].env) {
sails.log.debug('Environment is in result');
// if the current inspected value has been deployed later than the stored one
if (res[idx].updatedAt < json[idx].updatedAt) {
sails.log.debug('Updating the value in the result');
//res[json[idx].lifeCycle] = JSON.parse('{"'+json[idx].version+'":"'+json[idx].updatedAt+'"}');
res.env = json[idx].lifeCycle;
res.ver = json[idx].version;
res.updatedAt = json[idx].updatedAt;
}
} else {
// it is the first time we are adding to the result the component version (for the given environment)
if (json[idx].lifeCycle) {
//add the value in result
res[idx].env = json[idx].lifeCycle || '';
res[idx].ver = json[idx].version || '';
res[idx].updatedAt = json[idx].updatedAt || '';
}
else {
sails.log.debug('Lifecycle is null or empty');
}
}
}
return res;
This code receives a JSON with more than 1 element in it that has many values. After doing my checks, it goes to the bottom line where it says
if (json[idx].lifeCycle) {
//add the value in result
res[idx].env = json[idx].lifeCycle || '';
res[idx].ver = json[idx].version || '';
res[idx].updatedAt = json[idx].updatedAt || '';
}
In here, IDX is equals to 1 (second time coming around the for loop).
When I try to insert the second value to "res", i get error:
TypeError: Cannot read property 'env' of undefined
It's as if res didn't exist anymore after doing the first pass through the for loop.
Can anyone help me out and lemme know why this is happening?
Thanks so much!