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?
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.
Lodash first and last array elements head functions return the first array element; the _. last function returns the last array element.
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.
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])
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With