0
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?)

4
  • Here: jsfiddle.net/ofby394t Commented Jul 24, 2022 at 13:42
  • similar to lodash set youmightnotneed.com/lodash#set Commented Jul 24, 2022 at 13:46
  • "initially one would list the keys of the first object "level", then check if any of those keys is in the id string" - no. Just look at the first name in the path, and check whether it exists in the object. Do not enumerate all keys of the object. "then move to the next level, kind of screams for recursion?" - yes. Commented Jul 24, 2022 at 14:05
  • Please show us your attempt. Commented Jul 24, 2022 at 14:08

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

@KimSkogsmo That doesn't create "missing" objects like the answer does
Btw to really save bytes, write (o,k)=>o[k]??={}
@Bergi Oh, damn, I didn't see the assignment, read that too fast :P Nice fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.