ArticleZip > Equivalent Of Underscore _ Pluck In Pure Javascript

Equivalent Of Underscore _ Pluck In Pure Javascript

In JavaScript, the equivalent of underscore's pluck method can be achieved using a combination of map and destructuring. If you've ever worked with underscore.js, you might be familiar with the handy pluck method that allows you to extract specific properties from an array of objects. While there isn't a direct pluck method in vanilla JavaScript, you can easily replicate its functionality with a few lines of code.

To simulate the pluck functionality, you can use the map method along with destructuring to extract the desired property from each object in the array. Here's how you can accomplish this:

Javascript

const data = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

const pluck = (arr, key) => arr.map(({ [key]: value }) => value);

const names = pluck(data, 'name');
console.log(names); // Output: ['Alice', 'Bob', 'Charlie']

In the example above, we define a function called pluck that takes an array and a key as arguments. Within the function, we use the map method to iterate over each object in the array. By using destructuring `{ [key]: value }`, we extract the value of the specified key from each object and return it as a new array.

This approach allows you to extract specific properties from objects in an array without the need for an external library like underscore.js. It's a clean and concise way to achieve the same result using pure JavaScript.

Additionally, you can enhance the flexibility of the pluck function by adding error handling to check if the specified key exists in each object:

Javascript

const pluck = (arr, key) => arr.map(obj => obj.hasOwnProperty(key) ? obj[key] : undefined);

By including this additional check with `obj.hasOwnProperty(key)`, you can handle cases where the specified key is missing in an object, ensuring that your function behaves as expected even with inconsistent data.

Remember that simplicity and readability are key principles in writing effective and maintainable code. By understanding the underlying mechanisms of JavaScript and leveraging its features creatively, you can replicate the functionality of utility libraries like underscore.js in a pure JavaScript environment.

So, the next time you need to pluck specific properties from an array of objects in your JavaScript project, reach for the map method and destructuring to achieve the same outcome efficiently and elegantly. Happy coding!

×