John John - 11 months ago 117
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');
alert(a);


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

Answer Source

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, '').
        split('.').
        reduce((o, k) => (o || {})[k], object);
}

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

console.log(a);