简体   繁体   English

如何将 Underscore.js 过滤器与对象一起使用?

[英]How to use Underscore.js filter with an object?

I have an object like so:我有一个像这样的对象:

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

etc.. ETC..

How can I use the underscore _.filter() to return back only the items where selected === true?如何使用下划线_.filter()仅返回选择 === true 的项目?

I've never had the need to go down to layers with _.filter() .我从来不需要使用_.filter()深入到层。 Something like就像是

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

Thank you谢谢

If you want to pull all array elements from any e-mail address where selected is true , you can iterate like so:如果要从selectedtrue的任何电子邮件地址中提取所有数组元素,则可以像这样进行迭代:

var selected = [];

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

If you only want to pull the arrays where all elements are selected , you might instead do something like this:如果您只想拉取所有元素都被selected的数组,您可以改为执行以下操作:

var stuff = _.filter(me.collections, function(item) {
    return _.all(item, function (jtem) { 
        jtem.selected === true;
    });
});

Underscore's filter method will work on an object being used as a hash or dictionary, but it will return an array of the object's enumerable values and strip out the keys. Underscore 的 filter 方法将作用于用作散列或字典的对象,但它会返回对象的可枚举值的数组并删除键。 I needed a function to filter a hash by its values that would preserve the keys, and wrote this in Coffeescript:我需要一个函数来通过它的值过滤散列,以保留键,并在 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

If you're not using Coffeescript, here's the compiled result in Javascript, cleaned up a little:如果你不使用 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; TL; DR: Object.keys() is great! DR: Object.keys()很棒!

I have an object called allFilterValues containing the following:我有一个名为 allFilterValues 的对象,其中包含以下内容:

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

This is ugly but you asked for an underscore based way to filter an object.这很难看,但是您要求使用基于下划线的方式来过滤对象。 This is how I returned only the filter elements that had non-falsy values;这就是我只返回具有非假值的过滤器元素的方式; you can switch the return statement of the filter to whatever you need:您可以将过滤器的返回语句切换为您需要的任何内容:

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

Output (JSON/stringified):输出(JSON/字符串化):

{"originDivision":"GFC"}

@Dexygen was right to utilize _.pick but a cleaner solution is possible because the function also accepts a predicate @Dexygen 使用_.pick是正确的,但更清洁的解决方案是可能的,因为该函数还接受谓词

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}
const obj = {
    1 : { active: true },
    2 : { active: false },
    3 : { active: false },
}

let filtered = Object.entries(obj).reduce((acc, current) => {
    const currentEntry = current[1];
    const currentKey = current[0];
    //here you check condition
    if (currentEntry.active) {
      return {
        ...acc,
        [currentKey]: currentEntry
      }
    }
    return acc;
}, {})

There is a rule of thumb, if you need to achieve something really exotic look up into reducer it can solve almost all problems related to objects, it's a bit tricky to get used to it, but trust me thorough reading of documentation gonna pay off.有一条经验法则,如果你需要实现一些非常奇特的东西,请查看 reducer,它可以解决几乎所有与对象相关的问题,要习惯它有点棘手,但相信我彻底阅读文档会得到回报。

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

_.filter(me.collections, { selected: true})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM