I'm trying to recreate the Underscore pluck function using pure JS. However, I keep getting an array of undefineds being returned, instead of the actual values from the properties of the objects in an array.
Checking another thread here I found that you could reproduce it in jQuery with the following code...
$.pluck = function(arr, key) { return $.map(arr, function(e) { return e[key]; }) }
...however I am having difficulty just reproducing this in pure JS. I tried the following, however this is just returning an array of undefineds for me.
var pluck = function(arr,key){ var newArr = []; for (var i = 0, x = arr.length; i < x; i++){ if (arr[i].hasOwnProperty(key)){ newArr.push(arr[i].key) } } return newArr; }
So, the goal would be the following, except instead of using the underscore _.pluck, just use a JS function name, eg. var pluck = function(arr,key){...}
var Tuts = [{name : 'NetTuts', niche : 'Web Development'}, {name : 'WPTuts', niche : 'WordPress'}, {name : 'PSDTuts', niche : 'PhotoShop'}, {name : 'AeTuts', niche : 'After Effects'}]; var niches = _.pluck(Tuts, 'niche'); console.log(niches); // ["Web Development", "WordPress", "PhotoShop", "After Effects"]
Could someone steer me in the right direction?
OSCC · JavaScript, Array, Object · Oct 22, 2020. Converts an array of objects into an array of values corresponding to the specified key .
The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.
Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications.
The underscore is simply a valid character in an identifier, so the method's name is _render . The method Foo can then only be called from within the class which defined it. In JavaScript you can't do this, so it's a typical design pattern to prefix the method with _ to show that it should be treated as private.
In ES5:
function pluck(array, key) { return array.map(function(obj) { return obj[key]; }); }
In ES6:
function pluck(array, key) { return array.map(o => o[key]); }
You can do it with the native JavaScript .map()
:
Array.prototype.pluck = function(key) { return this.map(function(object) { return object[key]; }); };
edit — modifying built-in prototype objects should be done with care; a better way to add the function (should you be OK with the idea of doing so in general) would be with Object.defineProperty
so that it can be made non-enumerable:
Object.defineProperty(Array.prototype, "pluck", { value: function(key) { return this.map(function(object) { return object[key]; }); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With