0

Is there a way to perform Javascript optional chaining on dynamic path.

say I have, a dynamicPath = 'information.person.names.first_name'

If the path was known, I could have done data?.information?.person?.names?.first_name

I have searched and found out that if we have a single path, say dynamicPath = 'first_name' We can easily do data?.[dynamicPath] and get the value.

Can we have some way of doing data?.[dynamicPath] or something similar with the entire path of the object? If the value is 'information.person.names.first_name' then JS would treat the entire string as a key and value would be undefined.

I know we can achieve this with lodash _.get method but we are trying to avoid its use.

subodhkalika
  • 616
  • 4
  • 9
  • Optional chaining won't really be relevant here (although you could use it in a small way), because you'll split the string and then have a loop. See the linked question's answers, but basically: `let value = data; for (const part of path.split(".")) { value = value?.[part]; } console.log(value);` will give you `"Joe"` if that's the value of `first_name` and each part of that path on `data` is non-`null`, non-`undefined` (and `undefined` if any part is `null` or `undefined`). – T.J. Crowder Mar 15 '22 at 07:29

0 Answers0