相当于纯 JavaScript 中的 Underscore _.pluck [英] Equivalent of Underscore _.pluck in pure JavaScript
问题描述
我正在尝试使用纯 JS 重新创建 Underscore pluck 函数.但是,我一直在返回一个未定义数组,而不是数组中对象属性的实际值.
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.
检查另一个线程 here 我发现您可以使用以下代码在 jQuery 中重现它...
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]; })
}
...但是我很难在纯 JS 中重现它.我尝试了以下操作,但这只是为我返回一组未定义的.
...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;
}
因此,目标将如下所示,除了不使用下划线 _.pluck,只需使用 JS 函数名称,例如.var pluck = function(arr,key){...}
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?
推荐答案
在 ES5 中:
function pluck(array, key) {
return array.map(function(obj) {
return obj[key];
});
}
在 ES6 中:
function pluck(array, key) {
return array.map(o => o[key]);
}
这篇关于相当于纯 JavaScript 中的 Underscore _.pluck的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!