Home > OS >  Programmatically traverse JavaScript object and replace part of it
Programmatically traverse JavaScript object and replace part of it

Time:07-25

let tObj = {
     "name" : "testName",
     "location" : {
        "name": "nextLevelName",
        "address" : {
            "street" : "deep street"
        }
    }
}

let id = "location-address-street";
let newValue = "another deep street";

In the JavaScript object above I'd like to replace the street. I want this to be done by a function that can replace any value in any object given an object and the id string which contains the unique keys separated by "-" that lead to the property which value needs to be replaced. I am thinking that initially one would list the keys of the first object "level", then check if any of those keys is in the id string, if so move to the next level, etc. (kind of screams for recursion?)

CodePudding user response:


const keysDeep = id.split("-")

keysDeep.slice(0, -1).reduce((obj, key) => {
  if (!(key in obj)) return obj[key] = {}

  return obj[key]
}, tObj)

[keysDeep[keysDeep.length -1]] = newVal
  • Related