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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…