Sometimes, we want to select by object path with Lodash and JavaScript.
In this article, we’ll look at how to select by object path with Lodash and JavaScript.
How to select by object path with Lodash and JavaScript?
To select by object path with Lodash and JavaScript, we can use the get
method.
For instance, we write:
const obj = {
foo: 'bar',
count: '3',
counter: {
count: '3',
},
baz: {
test: "qux",
tester: {
name: "Ross"
}
}
};
const result = _.get(obj, 'baz.tester.name', 'defaultVal');
console.log(result)
We call get
with the object we want to find the property value for, the path to the property value, and the default value returned when the property isn’t found respectively.
Therefore, result
is 'Ross'
since obj.baz.tester.name
is 'Ross'
.
Conclusion
To select by object path with Lodash and JavaScript, we can use the get
method.