Reputation: 2893
I am trying to do something in pure JS. I have an Object like so
var data = {
"Something": true,
"Something else": false,
"Blah": false,
"a fish ISA": true
};
What I want to do is filter anything which has true to its own Object. At the moment I am trying
var thingFunctions = Object.keys(data).filter(function(e) {
return typeof data[e] == 'function'
});
But I think this is incorrect. How can I get the data with a value of true to its own Object?
Thanks
Upvotes: 2
Views: 103
Reputation: 24
To get a new object instead of just an array of the keys that point to a value of true
(not truthy such as 1
or "hello"
):
var onlyTrues = {};
for (var prop in data) {
if (data[prop] === true) {
onlyTrues[prop] = data[prop];
}
}
Upvotes: 0
Reputation: 4217
As you want to only have all true value we can convert them to true false values by doing the following.
!!({}) // true
!!([]) // true
!!('') // false
!!(true) // true
!!(false) // false
...
With this we can see if any data type is true or false by doing the following.
var thingFunctions = Object.keys(data).filter(function(e) {
return !!(data[e]);
});
Upvotes: 3
Reputation: 386604
You were asking for an object.
I use Array.prototype.forEach()
for the iteration over the keys and an empty object for the result filtered
, because I can not filter objects:
var data = {
"Something": true,
"Something else": false,
"Blah": false,
"a fish ISA": true
},
filtered = {};
Object.keys(data).forEach(function(e) {
if (data[e] === true) { // explicit testing for boolean and true!
filtered[e] = data[e];
}
});
document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');
Upvotes: 3
Reputation: 7553
So firstly you have no functions inside data
, so doing a check on functions will return nothing.
var data = {
"Something": true,
"Something else": false,
"Blah": false,
"a fish ISA": true
};
var thingFunctions = Object.keys( data ).filter(function( e ) {
return data[ e ] === true;
});
console.log( thingFunctions );
// Will result in [ 'Something', 'a fish ISA' ]
Upvotes: 3