How to use Optional Chaining if path is variable?

Viewed 148

Okay, so with ES11 I can now replace:

const name = _.get(response, 'data.options.name');

with:

const name = response?.data?.options?.name;

But how can I use do this, if 'data.options.name' is passed as variable?

For example, how can I easily (one-line) replace lodash in the following case?

async someFunc(doc, path) {
    let prop = _.get(doc, path);
    if (prop) {
        await doSomethingUseful(prop);
    }
}
1 Answers

You could split the path at . and reduce the parts. Start with doc object as the accumulator and return the nested object in each iteration with optional chaining

let prop = path.split(".").reduce((acc, part) => acc?.[part], doc)

const get = (doc, path) => path.split(".").reduce((acc, part) => acc?.[part], doc)

console.log(
  get({ data: { } }, 'data.options.name'),
  get({ data: { options: {} } }, 'data.options.name'),
  get({ data: { options: { name: 'abc' } } }, 'data.options.name')
)

Related