I am trying to look up parameters in an object through an array listing keys. For example, given an object {a: {b: {c: 3}}} and array ['a','b','c'], I am looking for a function that can recursively look through the object and in this example return 3. This is easy enough to do by looping through the array and defining a sub-object like this:
function keyChain(obj, chain) {
let subObject = obj;
for (let i = 0; i < chain.length; i++) {
if(subObject[chain[i]] !== undefined){
subObject = subObject[chain[i]];
}
}
return subObject;
}
However, the problem arises when you try to edit this parameter. Is there any function (without using eval) that could retain a deep reference or allow some other way to edit the value inside the object?
I have a working function to edit the value with eval. But, I'm running untrusted user input through this function so if some other safer solution exists it would be preferable.
function applyToKeyChain(obj, chain, value){
let lookUpString = '';
for(let i = 0; i < chain.length; i++){
loopUpString += '[' + chain[i] + ']';
}
eval(`obj${lookUpString} = value;`);
}
I've also tried retaining a deep reference to the object via getters and setters and another attempt keeping track of each sub-object in an array. Looping through the object to one key before the last and then manually looking up the key didn't work either.
The key is to traverse the nested object iteratively until (stopping before) the last element. Then, it is simple to set the value for the very last property in the chain.
function setNestedVal(obj, chain, val) {
const last = chain.pop();
chain.reduce((acc, k) => acc[k], obj)[last] = val;
}
let o = {a: {b: {c: 3}}};
setNestedVal(o, ['a','b','c'], 4);
console.log(o);