10

我有一个像这样的对象:

> Object
  > Rett@site.com: Array[100]
  > pel4@gmail.com: Array[4]
    > 0
       id : 132
       selected : true
    > 1
       id : 51
       selected : false

ETC..

如何使用下划线_.filter()仅返回选择 === true 的项目?

我从来不需要使用_.filter(). 就像是

var stuff = _.filter(me.collections, function(item) {
    return item[0].selected === true;
});

谢谢

4

5 回答 5

9

selected如果要从is的任何电子邮件地址中提取所有数组元素,则true可以像这样进行迭代:

var selected = [];

for (email in emailLists) {
    selected.concat(_.filter(emailLists[email], function (item) {
        return item.selected === true;
    }));
}

如果您只想拉出所有元素所在的数组,则selected可以改为执行以下操作:

var stuff = _.filter(me.collections, function(item) {
    return _.all(item, function (jtem) { 
        jtem.selected === true;
    });
});
于 2012-07-28T02:27:54.873 回答
5

Underscore 的过滤器方法将作用于用作散列或字典的对象,但它会返回对象的可枚举值的数组并删除键。我需要一个函数来通过保留键的值过滤散列,并在 Coffeescript 中写了这个:

hash_filter: (hash, test_function) ->
  keys = Object.keys hash

  filtered = {}
  for key in keys
    filtered[key] = hash[key] if test_function hash[key]
  filtered

如果你不使用 Coffeescript,这里是用 Javascript 编译的结果,稍微清理一下:

hash_filter = function(hash, test_function) {
  var filtered, key, keys, i;
  keys = Object.keys(hash);
  filtered = {};
  for (i = 0; i < keys.length; i++) {
    key = keys[i];
    if (test_function(hash[key])) {
      filtered[key] = hash[key];
    }
  }
  return filtered;
}


hash = {a: 1, b: 2, c: 3};
console.log((hash_filter(hash, function(item){return item > 1;})));
// Object {b=2, c=3}

TL; DR:Object.keys()很棒!

于 2014-08-22T21:56:45.440 回答
1

我有一个名为 allFilterValues 的对象,其中包含以下内容:

{"originDivision":"GFC","originSubdivision":"","destinationDivision":"","destinationSubdivision":""}

这很难看,但您要求使用基于下划线的方式来过滤对象。这就是我只返回具有非虚假值的过滤器元素的方式;您可以将过滤器的返回语句切换为您需要的任何内容:

    var nonEmptyFilters = _.pick.apply({}, [allFilterValues].concat(_.filter(_.keys(allFilterValues), function(key) {
        return allFilterValues[key];
    })));

输出(JSON/字符串化):

{"originDivision":"GFC"}
于 2013-08-28T21:42:24.310 回答
1

@Dexygen was right to utilize _.pick but a cleaner solution is possible because the function also accepts a predicate

Return a copy of the object, filtered to only have values for the allowed keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.

(highlight is mine)

Here's a real life example I've used in a project

_.pick({red: false, yellow: true, green: true}, function(value, key, object) {
    return value === true;
});
// {yellow: true, green: true}
于 2021-03-02T13:34:57.927 回答
-2

也许你想要一个最简单的方法

_.filter(me.collections, { selected: true})
于 2016-08-12T14:31:24.163 回答