Categories
JavaScript Answers

How to select by object path with Lodash and JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *