EN
JavaScript - equivalent of Underscore.js _.pluck in pure JS
1
answers
0
points
Is there any equivalent of Underscore.js _.pluck() method in pure JS?
I need one method to pass two arguments array and property to it and receive the property values, for example:
var users = [
{ id: 101, name: 'Ann', },
{ id: 102, name: 'Tom', },
{ id: 103, name: 'Kate' }
];
console.log(_.pluck(users, 'id'));
result:
[ 101, 102, 103 ]
1 answer
0
points
You can use map() method to create a custom pluck() function in pure JavaScript.
Practical examples
ES6+ solution:
// ONLINE-RUNNER:browser;
const pluck = (array, property) => {
return array.map((object) => object[property]);
};
// Usage example:
const users = [
{ id: 101, name: 'Ann' },
{ id: 102, name: 'Tom' },
{ id: 103, name: 'Kate' },
];
console.log(pluck(users, 'id')); // [ 101, 102, 103 ]
For older versions of JavaScript:
// ONLINE-RUNNER:browser;
function pluck(array, property) {
return array.map(function(object) {
return object[property];
});
}
// Usage example:
var users = [
{ id: 101, name: 'Ann' },
{ id: 102, name: 'Tom' },
{ id: 103, name: 'Kate' },
];
console.log(pluck(users, 'id')); // [ 101, 102, 103 ]
References
0 comments
Add comment