lodash _.get function in typescript

12,106

In plain 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);
Share:
12,106

Related videos on Youtube

John
Author by

John

Updated on June 04, 2022

Comments

  • John
    John almost 2 years

    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?

  • caesay
    caesay over 6 years
    This does not appear to handle arrays.
  • ßãlãjî
    ßãlãjî almost 4 years
    this is exacty what i want, i tested nested and array of object working perfect my needs