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

The _.propertyOf() function in the Underscore library returns a function that can be used to extract a specific property from an object. Here's an example of how to use it:

index.tsx
// Load the underscore library
const _ = require('underscore');

// Define an array of car objects
const cars = [
  { make: 'Honda', model: 'Civic', year: 2015 },
  { make: 'Toyota', model: 'Corolla', year: 2017 },
  { make: 'Ford', model: 'Mustang', year: 2012 }
];

// Create a function that extracts the 'year' property from an object
const getYear = _.propertyOf(cars[0]);

// Use the function to get the year of the first car in the array
const year = getYear('year');
console.log(year); // Output: 2015
509 chars
17 lines

In this example, we first load the Underscore library. We then define an array of car objects, each with a 'make', 'model', and 'year' property. We then use _.propertyOf() to create a function getYear that can be used to extract the 'year' property from any car object. Finally, we use getYear to get the year of the first car in the array and log it to the console.

gistlibby LogSnag