Languages

JavaScript - equivalent of Underscore.js _.pluck in pure JS

0 points
Asked by:
Violetd
925

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
Answered by:
Violetd
925

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

  1. Array.prototype.map() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join