So I am trying to accomplish turning an array of booleans to an array of strings, (only of the booleans that were set to true). This can be in either javascript, or underscore. Let me show you what I mean.
I have an array like this :
[{"item1" : [{"one": true, "two": false}]}, {"item2" : [{"one": false, "two": true}]}];
And the end result I am looking for is :
[{"item1" : ["one"]}, {"item2" : ["two"]}];
It's worth mentioning, all of these keys will be dynamic. I can't seem to figuire out how I should traverse this array to complete this task. The simpler, the better! Thanks!
Here's my poor attempt :
$scope.testObject = _.map($scope.filterArray, function(obj) {
_.map(obj.values, function(value) {
if (value === true) {
return value;
}
});
});
(this does not work). What I am trying to accomplish is turning the values of these objects ([{"one":true, "two": false}] for example) into an array of strings, the strings being the keys of the items that are set to true.
So for example
[{"one":true, "two": false}]
would turn into
["one"]
Because two is false.
With lodash:
1) pick the properties of an object whose value is truthy:
2) grab the keys of the properties of an object whose value is truthy: (combining with the solution above)
3) do the above operation for each
item
with_.mapValues
(which is like performingArray.prototype.map
on objects)update: With underscore:
Fortunately most of the methods are supported by underscore, the only change I had to do was to change
_.mapValues
to_.mapObject
(source)This function will allow you to generate the result you need. 'For in' is useful for accessing object keys I did that twice. It may be that there is a more elegant way of implementing this feature. If you give me more information, I could try and help you?'
JavaScript set object key by variable