javascript 使用 lodash 查找具有真值的 JS 对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29441173/
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-10-28 10:32:32  来源:igfitidea点击:

Find properties of JS object with truthy values using lodash

javascriptlodash

提问by Asmor

Let's say I have an object like:

假设我有一个对象,例如:

var foo = {
    alpha: true,
    beta: false,
    gamma: true
}

I can use _.findKey to get one key with a true value, but I'd really like to get an array containing all keys with a true value. E.g.

我可以使用 _.findKey 来获得一个具有真值的键,但我真的很想获得一个包含所有具有真值的键的数组。例如

_.findAllKeys(foo, function(val) { return val; });
// yields -> ["alpha", "gamma"]

It's simple enough to write a function to do this, but it seems like such an obvious generalization of findKey that I feel I must just be missing it. Does lodash have such a function?

编写一个函数来执行此操作很简单,但它似乎是对 findKey 如此明显的概括,我觉得我一定只是错过了它。lodash有这样的功能吗?

回答by DTing

var foo = {
    alpha: true,
    beta: false,
    gamma: true
};

var t1 = _.keys(_.pick(foo, _.identity));
console.log(t1);

var t2 = _(foo).pick(_.identity).keys().value();
console.log(t2);
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Edit:
As noted by @backdesk, _.pickno longer works for lodash 4 because _.pickBywas split out.

编辑:
正如@backdesk 所指出的,_.pick不再适用于 lodash 4,因为它_.pickBy被拆分了。

var foo = {
    alpha: true,
    beta: false,
    gamma: true
};

var t1 = _.keys(_.pickBy(foo, _.identity));
console.log(t1);

var t2 = _(foo).pickBy(_.identity).keys().value();
console.log(t2);

// _.pickBy defaults to _.identity

var t3 = _.keys(_.pickBy(foo));
console.log(t3);

var t4 = _(foo).pickBy().keys().value();
console.log(t4);
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.8.2/lodash.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

回答by Asmor

I found an answer which simultaneously feels kludgy and elegant.

我找到了一个同时感觉笨拙和优雅的答案。

var foo = {
    alpha: true,
    beta: false,
    gamma: true
};
_.invert(foo, true).true

// yields -> ["alpha", "gamma"]

回答by Adam

pickByin loDash by default uses _.identityto filter properties so you can use it like this:

loDash中的 pickBy 默认用于_.identity过滤属性,因此您可以像这样使用它:

_.pickBy({'a': undefined, 'b':1, c:{}});

// => Object {b: 1, c: Object}

回答by AWolf

I think you're looking for the pickmethod.

我想你正在寻找pick方法。

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

返回对象的副本,过滤后仅包含白名单键(或有效键数组)的值。或者接受一个指示选择哪些键的谓词。

var foo = {
    alpha: true,
    beta: false,
    gamma: true
};

var picked = _.pick(foo, function(value) { return value; });
console.log(picked);

$('#output').html(JSON.stringify(picked));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.js"></script>
<div id="output">
</div>

回答by Subrata Sarkar

We can use pickBy() in lodash to get the key for which value equal to true.

我们可以在 lodash 中使用 pickBy() 来获取值等于 true 的键。

const active = _.keys(_.pickBy(foo));

Alternatively we can also use,

或者我们也可以使用,

var active = _.keys(foo).filter(function (id) {
    return foo[id]
});

回答by Vincent van der Weele

I personally prefer the following - even though it is more verbose - because I think it is more obvious what it does. It requires es6 syntax, though:

我个人更喜欢以下内容 - 尽管它更冗长 - 因为我认为它的作用更明显。不过,它需要 es6 语法:

_.toPairs(foo)
  .filter([key, value] => value)
  .map([key, value] => key);


If your ESLint does not allow unused variables you can for instance use the following in .eslint.yml:

如果您的 ESLint 不允许未使用的变量,您可以例如在以下内容中使用.eslint.yml

rules:    
  no-unused-vars:
    - 2
    - vars: all
      args: after-used
      argsIgnorePattern: _$

Which allows to write

这允许写

_.toPairs(foo)
  .filter([key_, value] => value)
  .map([key, value_] => key);

回答by Walter Zalazar

Just try

你试一试

var foo = {
    alpha: true,
    beta: false,
    gamma: true
}

_.pickBy(foo, _.identity);

_.pickBy(foo, _.identity);