_.pluck在找不到对象时给出一个未定义值的数组

时间:2015-02-27 06:58:49

标签: javascript lodash

我正在使用lodash中的_.pluck()来获取数组中键的值。

var employees = [
  {
    Name : "abc"  
  },
  {
    Name : "xyz"
  }
]

var res = _.pluck(employees, 'Name'); 

变量res将包含['abc,'xyz']

当我搜索其他字段时

var res = _.pluck(employees, 'SomeRandomField');   

结果 - [未定义,未定义]

如何将上述结果视为undefined而不是数组的null 未定义的值

Plnkr:http://plnkr.co/edit/qtmm6xgdReCuJP5fm1P2?p=preview

3 个答案:

答案 0 :(得分:6)

您可以使用filterpluck

var res = _.filter(_.pluck(employees, 'Name'), function(item) {
    return item;
});

答案 1 :(得分:2)

您可以使用compact()从弹出的数组中删除 falsey 值。您可以使用thru()来更改包装器的输出。在这种情况下,如果所有提取的值均为null,我们需要undefined

var collection = [ {}, {}, {} ];

_(collection)
    .pluck('foo')
    .compact()
    .thru(function(coll) { return _.isEmpty(coll) ? null : coll; })
    .value();
// → null

答案 2 :(得分:1)

我看起来好像在寻找.some功能:

var res = _.pluck(employees, "Name");
res = res.some(function (d) { return d }) ? // are any of the elements truth-y?
    // if so, map the  false-y items to null
    res.map(function (item) { return item || null; }) :
    // otherwise (no truth-y items) make res `null`
    null;

我看了.pluck的lodash文档,我不相信这是可能的。

  

_.pluck(collection, key)

     

参数   collection (Array | Object | string):要迭代的集合。

     

key(string):要拔除的属性的键。

您可以改为.pluck然后使用JavaScript内置(或lodash' s).map

var res = _.pluck(employees, 'Name').map(function (d) {
    return d ? d : null;
});

这是相当低效的。您也可以编写自己的函数,只迭代数组一次:

_.nullPluck = function (arr, key) {
    return arr.map(function (d) {
        return d && d[key] ? d[key] : null;
    }) 
}