Batman Batman - 3 months ago 20
Javascript Question

Updating nested object properties

I'm trying to update the value of a nested object.

Object:

var data = {
"key 1": {
"jan-16": 0,
"feb-16": 0,
"mar-16": 0
},
"key 2": {
"jan-16": 0,
"feb-16": 0,
"mar-16": 0
}
}

data["key 1"]["jan-16"] += 250;


The problem is that all I'm doing is adding 0 + 250 but not actually updating the object value

This is how I'm trying to do it with other code:

if(firstBillDate.isBefore(dateEnd)) {
while(intervalIterator > 0) {
let targetService = report[service][monthInterval];
if( !_.isNull(targetService) && !_.isUndefined(targetService) ) {
targetService += cost; // Nothing is happening here
monthInterval = moment(monthInterval).add(pmtInterval,'month').format('MMMM-YYYY');
intervalIterator -= pmtInterval; //12-4
}
}
}


enter image description here

qxz qxz
Answer

When you do:

let targetService = report[service][monthInterval];

Because the value of that property is a primitive number (i.e., not a reference type), targetService creates a clone of the value, not a reference to it. Therefore, incrementing targetService only changes targetService, not the original object.

Just replacing the problem line with report[service][monthInterval] += cost; should work. I don't think there is a more elegant way to do that.

Comments