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?
10
Answers
You are so close. You need to change:
to:
Consider this:
Hope you get my point.
You can do it with the native JavaScript
.map()
: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:Here’s a working solution
I didn’t really change all that much. The reason why your code failed is because you used the dot operator
.key
to access the named property of the array elements instead of the bracket operator[key]
. When using a reference as a key you need to use the bracket operator.How about a reduce:
In ES5:
In ES6:
JSFiddle
You can use this function, click in JSFiddle to see a Example!! 🙂
Here’s an example of doing
_.pluck(Tuts, 'name');
If you want to remove the undefined values in the case that there is no
name
in the object, you can use a.filter()
afterwardHow about using Proxy?
Here’s an example of doing _.pluck(Tuts, ‘name’);
If you want to remove the undefined values in the case that there is no name in the object, you can use a .filter() afterward
Just plain simple without the need to use methods:
This is combined function for some cases when you need an object with key value:
Example:
It will return: