简体   繁体   English

根据值获取对象键

[英]Get object keys based on value

I have a use case where I have an object of varying values, and I need to get all of these keys that have a specific value. 我有一个用例,其中有一个可变值的对象,我需要获取所有具有特定值的键。 For instance, here is a sample object: 例如,这是一个示例对象:

myObject = {
    Person1: true,
    Person2: false,
    Person3: true,
    Person4: false
};

The key names will vary, but the valid values are true or false. 密钥名称会有所不同,但是有效值为true或false。 I want to get an array of the names that have a value of true: 我想获取名称为true的名称的数组:

myArray2 = [
    'Person1',
    'Person3
];

I've been trying to use various lodash functions in combination such as _.key() and _.filter, but with no luck. 我一直在尝试结合使用各种lodash函数,例如_.key()和_.filter,但是没有运气。 How can I accomplish this? 我该怎么做? I'm open to pure JS or Lodash options. 我愿意接受纯JS或Lodash选项。

UPDATE: I accepted mhodges' answer below as the accepted answer, although others gave me the same answer. 更新:我接受了下面mhodges的答案作为接受的答案,尽管其他人也给了我相同的答案。 Based on that, I came up with a Lodash version: 基于此,我想出了Lodash版本:

var myArray = _(myObject).keys().filter(function(e) {
    return myObject[e] === true;
}).value();

If I understand your question correctly, you should be able to use basic .filter() for this. 如果我正确理解了您的问题,则应该可以使用基本的.filter()

myObject = {
    Person1: true,
    Person2: false,
    Person3: true,
    Person4: false
};

var validKeys = Object.keys(myObject).filter(function (key) { 
    return myObject[key] === true; 
});

Use Object.keys(): 使用Object.keys():

var object = {
    1: 'a',
    2: 'b',
    3: 'c'
};
console.log(Object.keys(object));

Alternative solution: 替代解决方案:

var keys = [];
for (var key in object) {
    if (object.hasOwnProperty(key)) {
        keys.push(key);
    }        
}    
console.log(keys);

Don't forget to check a key with the help of hasOwnProperty() , otherwise this approach may result in unwanted keys showing up in the result. 不要忘了在hasOwnProperty()的帮助下检查key ,否则这种方法可能会导致不需要的keys出现在结果中。

You can do this with Object.keys() and filter() . 您可以使用Object.keys()filter()做到这一点。

 var myObject = { Person1: true, Person2: false, Person3: true, Person4: false }; var result = Object.keys(myObject).filter(function(e) { return myObject[e] === true; }) console.log(result) 

ES6 version with arrow function 具有箭头功能的ES6版本

var result = Object.keys(myObject).filter(e => myObject[e] === true)

Since Lodash was tagged: With pickBy the values can be filtered (and the keys obtained with _.keys ): 由于Lodash被标记为:使用pickBy可以过滤值(以及通过_.keys获得的键):

var myArray2  = _.keys(_.pickBy(myObject));

 var myObject = { Person1: true, Person2: false, Person3: true, Person4: false }; var myArray2 = _.keys(_.pickBy(myObject)); console.log(myArray2 ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

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

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