在纯粹的JavaScript下划线_.pluck等效 [英] Equivalent of Underscore _.pluck in pure JavaScript

查看:754
本文介绍了在纯粹的JavaScript下划线_.pluck等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重新使用纯JS下划线勇气功能。不过,我不断收到,而不是从阵列中的对象的属性的实际值返回undefineds的数组。

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.

检查另一个线程<一个href=\"http://stackoverflow.com/questions/9329114/equivalent-of-underscore-js-pluck-in-jquery%20'here'\">here我发现,你可以用下面的code重现它在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复制本。我尝试以下,然而这仅仅是返回undefineds数组我。

...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勇气=功能(ARR,键){...}

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?

推荐答案

您是如此接近。您需要更改:

You are so close. You need to change:

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

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.

这篇关于在纯粹的JavaScript下划线_.pluck等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆