Search code examples
javascriptjsontypescriptstringobject

Access and modify JSON-Object via string path


my question is simple but nobody in the web seemed to have answered it and I can't get my head around it.

I basically want to write a setter function which takes a JSON-Object and sets a key to a value, no matter if the path already exists or not.

Variant 1:

setPath(payload: Object, path: string, value: any) {
 // ???
}

obj: Object = {}
newObj: Object = setPath(obj, "foo.bar[0], "wut");

Variant 2:

setPath(payload: Object, path: string, value: any){
 // ???
}
obj: Object {
 foo: {
  bar: []
 }
}
newObj: Object = setPath(obj, "foo.bar[0]", "wut");

Where both of them would result in a JSON-Object looking like this:

{
 foo: {
  bar: [
   "wut" 
  ]
 }
}

Thanks for your help


Solution

  • Thanks to @cmgchess,

    https://youmightnotneed.com/lodash#set

    At this link you can either find a plain JavaScript solution or, as I did, just use the method lodash provides to you