Hi, I have a question:
can I set an obj property having the path of that proprety?
example:
let myobject = {
a: "a",
b: {
nested: "nested value"
}
}
let arr = ["b", "nested"];
function changeObjValue(obj, path, newValue){
if(path.length == 1){
obj[path[0]] = newValue;
}else if(path.length ==2){
obj[path[0]][path[1]] = newValue;
}else if (path.length == 3) {
obj[path[0]][path[1]][path[2]] = newValue;
}
return obj;
}
changeObjValue(myobject, arr, "new nested value");
this works but i’m looking for better solution;
example of returning the value using a loop.
function getObjValue(obj, path) {
let value = obj;
for (let i = 0; i < path.length; i++) {
value = value[path[i]];
}
return value;
}
I wanna do something similar but that allows to change that property.
Thank You!