Set obj proprety from an array

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!

  • If the path has only one entry, so it’s like [key], return the object with obj[key] set as newEntry.
  • If the path has more than one entry, so it’s like [key, ...keys], return the object with obj[key] set as the result of running changeObjValue, this time with the first argument being obj[key] and the second argument being keys
1 Like

Thank you! Works perfectly,
I think I understood why the recursion works and the for loop not,
Because when I assign obj = obj[path[i]] obj is no more related to the initial obj and if I change his property it doesn’t change the initial obj.
Right?

1 Like

Yep, basically with the recursion you’re drilling down until you hit the property, then walking back up and progressively replacing the entirety of the part of the object containing that property.

You can do it with a loop (probably a while loop tbh) in combination with something to track where you are (eg a stack). But important to note that you would be doing the same as the recursive solution (recursive algorithms can normally be rewritten using a loop + a stack)