Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
John Avatar asked Oct 20 '16 08:10

John


People also ask

What does _ get do?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place.

What does _ do in Lodash?

Lodash first and last array elements head functions return the first array element; the _. last function returns the last array element.

What is the point of Lodash get?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

What is _ find in JavaScript?

The _. find() function looks at each element of the list and returns the first occurrence of the element that satisfy the condition. If any element of list is not satisfy the condition then it returns the undefined value. Syntax: _.find(list, predicate, [context])


1 Answers

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);
like image 164
Nina Scholz Avatar answered Sep 22 '22 11:09

Nina Scholz