John John - 6 months ago 78
Javascript Question

lodash _.get function in typescript

I get the feeling after some googling that a lot of lodash's functions can be achieved with native typescript but i cannot find a straightforward answer for the _.get function...

In lodash the following, using the _.get function alerts 1

let obj = {a:{b:1}};
let a = _.get(obj, 'a.b');

Is there a way of achieving the same result with only typescript?


In pain Javascript you could split the path and reduce the path by walking the given object.

function getValue(object, path) {
    return path.
        replace(/\[/g, '.').
        replace(/\]/g, '').
        reduce((o, k) => (o || {})[k], object);

var obj = { a: { b: 1 } },
    a = getValue(obj, 'a.b');