how to use the property function from the underscore library in javascript

The property function from the Underscore.js library is a higher-order function that creates a function which returns a property value of a given object. It takes a string argument, which is the name of the property to access.

Here's an example usage of the property function:

index.tsx
const students = [
  { name: 'Alice', age: 20 },
  { name: 'Bob', age: 21 },
  { name: 'Charlie', age: 22 }
];

// Create a function that returns the 'age' property of an object
const getAge = _.property('age');

// Use the created function to get an array of ages
const ages = students.map(getAge); // [20, 21, 22]
316 chars
12 lines

In this example, the property function is used to create a function getAge that retrieves the age property of an object. The getAge function is then used with the map function to extract an array of ages from an array of student objects.

By using the property function, we can reduce the amount of boilerplate code needed to access object properties and make our code more concise and expressive.

gistlibby LogSnag