0

Problem

I want to build a function that takes in a path to a nested object value and sets that value to 'new value'

const obj = {
  foo: {
    bar: 'baz'
  }
}

// api should look like
changeObjKey(o => o.foo.bar)

//or
changeObjKey('foo.bar')

/*
* expected:
obj = {
  foo: {
    bar: 'new value'
  }
}
*/

What I've tried:

Something like this (which obviously doesn't work)

function changeObjKey(cb){
  cb(obj) = 'new value'
}

I don't want to use lodash or the likes, I'm looking for the most minimal solution to this problem. I also don't want to use eval and the api should support both foo.bar and foo[bar] (if its string based)

cubefox
  • 1,251
  • 14
  • 29

0 Answers0