我正在尝试使用纯JS重新创建下划线pluck函数。然而,我总是得到一个返回的未定义的数组,而不是数组中对象的属性的实际值。
检查另一个线程here时,我发现您可以用以下代码在jQuery中重现它……
$.pluck = function(arr, key) {
return $.map(arr, function(e) { return e[key]; })
}...however我很难在纯JS中重现它。我尝试了下面的方法,但是这只是为我返回了一个未定义的数组。
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){...}
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"]有人能给我指引正确的方向吗?
发布于 2016-05-08 02:55:58
在ES5中:
function pluck(array, key) {
return array.map(function(obj) {
return obj[key];
});
}在ES6中:
function pluck(array, key) {
return array.map(o => o[key]);
}发布于 2014-09-08 22:04:34
您可以使用本机JavaScript .map()执行此操作
Array.prototype.pluck = function(key) {
return this.map(function(object) { return object[key]; });
};编辑-修改内置的原型对象应该小心;添加函数的更好的方法(如果你一般这样做的想法是可以接受的)是使用Object.defineProperty,这样它就可以成为不可枚举的:
Object.defineProperty(Array.prototype, "pluck", {
value: function(key) {
return this.map(function(object) { return object[key]; });
}
});发布于 2014-09-08 22:03:58
你就差一步了。您需要更改:
newArr.push(arr[i].key);至:
newArr.push(arr[i][key]);请考虑以下内容:
var obj = { myKey: 'my Value', theKey: 'another value' };
var theKey = 'myKey';
alert(obj.theKey); // another value
alert(obj[theKey]); // my Value
// You can also send in strings here:
alert(obj['theKey']); // another value希望你能明白我的意思。
https://stackoverflow.com/questions/25726066
复制相似问题