相当于纯 JavaScript 中的 Underscore _.pluck

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25726066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:46:41  来源:igfitidea点击:

Equivalent of Underscore _.pluck in pure JavaScript

javascriptarraysunderscore.js

提问by wesleysmyth

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.

我正在尝试使用纯 JS 重新创建 Underscore pluck 函数。但是,我一直在返回一个未定义数组,而不是数组中对象属性的实际值。

Checking another thread hereI found that you could reproduce it in jQuery with the following code...

在此处检查另一个线程我发现您可以使用以下代码在 jQuery 中重现它...

$.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.

...但是我很难在纯 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;
}

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){...}

因此,目标将如下所示,除了不使用下划线 _.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"]

Could someone steer me in the right direction?

有人可以引导我朝着正确的方向前进吗?

回答by Gilles Castel

In ES5:

在 ES5 中:

function pluck(array, key) {
  return array.map(function(obj) {
    return obj[key];
  });
}

In ES6:

在 ES6 中:

function pluck(array, key) {
  return array.map(o => o[key]);
}

回答by Pointy

You can do it with the native JavaScript .map():

您可以使用本机 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.definePropertyso that it can be made non-enumerable:

编辑——修改内置原型对象应该小心;一个更好的添加函数的方法(如果你同意这样做的话)一般来说是Object.defineProperty这样的,这样它就可以成为不可枚举的:

Object.defineProperty(Array.prototype, "pluck", {
    value: function(key) {
        return this.map(function(object) { return object[key]; });
    }
});

回答by andlrc

You are so close. You need to change:

你是如此接近。你需要改变:

newArr.push(arr[i].key);

to:

到:

newArr.push(arr[i][key]);


Consider this:

考虑一下:

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

Hope you get my point.

希望你明白我的意思。

回答by FK82

Here's a working solution

这是一个有效的解决方案

function pluck(array,key){
  var a = [],
     i1 = -1, i2 = array.length,
      o ;

    while(++i1 < i2)
    {
        o = array[i1] ; // you have to use the bracket operator here
        if(o.hasOwnProperty(key)) a[a.length] = o[key] ;
    }
  return a ;
}

I didn't really change all that much. The reason why your code failed is because you used the dot operator .keyto 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.

我并没有真正改变那么多。您的代码失败的原因是您使用点运算符.key而不是括号运算符来访问数组元素的命名属性[key]。使用引用作为键时,您需要使用括号运算符。

回答by Jivings

How about a reduce:

减少怎么样:

$.pluck = function(arr, key) { 
    return arr.reduce(function(p, v) { 
      return p.concat(v[key]); 
    }, []); 
}

var people = [
  { name: 'James', age: 26 }, 
  { name: 'Fred', age: 56 }
];

$.pluck(people, 'age');
=> [26, 56]

$.pluck(people, 'name');
=> ['James', 'Fred']

回答by Pedro Monteiro Arantes

var array = {
name: ["Pedro", "Jo?o", "Francisco", "Diogo"],
ID: [1,2,3,4]
};
console.log(pluck(array,'name'));

function pluck(array, key) {
   return (array[key]);
};

JSFiddle

JSFiddle

You can use this function, click in JSFiddle to see a Example!! :)

你可以使用这个功能,在JSFiddle中点击查看示例!!:)