how to use the propertyof function from lodash in javascript

To use the propertyOf function from lodash in JavaScript, you need to first install lodash in your project. You can do this via npm by running the following command:

index.tsx
npm install lodash
19 chars
2 lines

Once installed, you can use the propertyOf function to create a function that returns the value of a property on an object. This is useful when you need to access a deeply nested property on an object, but you don't know if the object or any of its properties are null or undefined.

Here's an example of how to use propertyOf:

index.tsx
const _ = require('lodash');

const myObj = {
  foo: {
    bar: {
      baz: 'hello world',
    },
  },
};

const getBaz = _.propertyOf(myObj)('foo.bar.baz');

console.log(getBaz); // Output: 'hello world'
206 chars
14 lines

In this example, we first require lodash and create an object with a nested property called baz. We then use _.propertyOf(myObj) to create a function that takes a string argument representing a path to a property (in this case, 'foo.bar.baz'). We then immediately invoke this function with the path string to get the value of the baz property on myObj, which is 'hello world'.

Note that if any of the properties in the path string are null or undefined, the function will return undefined.

gistlibby LogSnag