I'm writing a function that will take in an object and modify a field within the object (could be a nested field). For instance, modifyObj(obj, 'nested.nested', 2) will essentially do obj.nested.nested = 2. The most straightforward way seems to be to use eval, but the consensus seems to be using eval is evil? http://jsfiddle.net/zntf6bfw/
function modifyObj(obj, field, val) {
var str = 'obj.' + field + '=' + val;
eval(str);
}
The alternative is to use regex to determine if the passed in field is nested, and if so, to use a loop to get a nested object and modify it (which will modify the overall object). However, this seems unnecessarily complicated, and would this count as a valid use case for eval?
function modifyObj2(obj, field, val) {
//if we are modifying a nested val
if (/\./g.test(field)) {
var arr = field.split('.'),
temp = obj;
//we want temp to be equal to the nested object holding the nested field to be modified and changing this will modify the passed in object
for (var i = 0; i < arr.length - 1; i++) {
temp = temp[arr[i]];
}
temp[arr.length - 1] = val;
}
//if we are modifying a non-nested val
else {
obj[field] = val;
};
}