0

So let's say there is an object a:

let a = {
  b: {
    c: {
      d: {
        e: null
      }
    }
  }
}

The task is to create a method which would be assigning a value to a-object's property by property's path that will be passed into method as string. So expected result is:

Method

let magicMethod = ({prop, value}) => {
  /*magic here*/
}

Call:

magicMethod({prop: 'b.c.d.e', value: true})

Result (console.log(a)):

{
  b: {
    c: {
      d: {
        e: true
      }
    }
  }
}

It should work for all deepness levels, so call magicMethod({prop: 'b.c', value: true}) should modify a-object to:

{
  b: {
    c: true
  }
}

Is there a way to achieve such behavior via recursion or something else?

So far, i did manage to implement it with this approach: enter image description here

But it is not flexible and, to be honest, i don't like it at all :) I have a feeling that there are some smarter solutions.

Andrew
  • 101
  • 1
  • 7
  • 1
    Also related (the one i usually take as dupe link): https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arays-by-string-path – ASDFGerte Apr 07 '20 at 15:24
  • 1
    eval('a.b.c.d.e=true') ?? i.e. eval (yourString + " = " + value) - which will work if structure exists that you specified in yourString, and is in scope – developer Apr 07 '20 at 15:25
  • @developer it works, but disregards major security concerns regarding `eval`, therefore is often not applicable. – ASDFGerte Apr 07 '20 at 15:30
  • @ASDFGerte point taken - However, the security concerns are usually in respect of unknown content being evaluated - in this situation the eval is on a known structure inside the yourString variable/structure in my comment – developer Apr 07 '20 at 15:35
  • @ASDFGerte: Note that your related question is about *getting* value by a dot-path. This one is about *setting* a value. Not that they're unrelated, but it will probably be very different code. – Scott Sauyet Apr 07 '20 at 19:00
  • @developer: Even ignoring the mantra that *eval is evil*, that won't work if some of the intermediate nodes are missing. Try it on `{a : b: {}}`, for instance. – Scott Sauyet Apr 07 '20 at 19:03
  • @ScottSauyet - you should read my comment closer - specifically the bit where i say: "will work if structure exists that you specified in yourString, and is in scope." (all the second half) – developer Apr 08 '20 at 09:28
  • @developer: That simply means that this technique is less useful than those described in many related questions. But `eval` might already be disqualifying. There are environments that prohibit any version of `eval` (even the Function constructor) altogether. – Scott Sauyet Apr 08 '20 at 12:42

0 Answers0