问题
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. I want to get an array of the names that have a value of true:
myArray2 = [
'Person1',
'Person3
];
I've been trying to use various lodash functions in combination such as _.key() and _.filter, but with no luck. How can I accomplish this? I'm open to pure JS or Lodash options.
UPDATE: I accepted mhodges' answer below as the accepted answer, although others gave me the same answer. Based on that, I came up with a Lodash version:
var myArray = _(myObject).keys().filter(function(e) {
return myObject[e] === true;
}).value();
回答1:
If I understand your question correctly, you should be able to use basic .filter()
for this.
myObject = {
Person1: true,
Person2: false,
Person3: true,
Person4: false
};
var validKeys = Object.keys(myObject).filter(function (key) {
return myObject[key] === true;
});
回答2:
Use 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.
回答3:
You can do this with Object.keys()
and 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
var result = Object.keys(myObject).filter(e => myObject[e] === true)
回答4:
Since Lodash was tagged: With pickBy
the values can be filtered (and the keys obtained with _.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>
来源:https://stackoverflow.com/questions/42794939/get-object-keys-based-on-value