The case is simple - I\'ve got a following object:
Object {1: false, 2: true, 3: false, 4: false, 5: false, 6: false, 7: false, 8: true, 12: false, 13: false, 14
I Do not know underscore.js
. But using normal JS, I have written the below code.
function myFunction()
{
var str="1: false; 2: true; 3: false; 4: false; 5: false; 6: false; 7: false; 9: true; 12: false";
var n=str.split(";");
for(var i=0;i<n.length;i++)
{
if(n[i].search("true")!=-1){
alert(n[i].slice(0,n[i].search(":")));
}
}
My version:
var list = {
1: false, 2: true, 3: false, 4: false,
5: false, 6: false, 7: false, 8: true,
12: false, 13: false, 14: false, 15: false,
16: false, 17: false, 18: false, 19: false
};
_.chain(list).map(function(val, key) {
return val ? parseInt(key) : undefined
}).reject(function(val) {
return _.isUndefined(val);
}).value();
// returns [2,8]
This might be easier
result = _.chain(obj)
.map(function(value, key){
return value?key:false;
})
.filter(function(v){
return v
})
.value();
You can try this:
_.pairs(obj)
.filter(function(pair) { return pair[1] })
.map(function(pair) { return pair[0] })
Or the same but bit more concise:
_.pairs(obj).filter(_.last).map(_.first)
Another potential solution:
// Your example data
var data = {1: false, 2: true, 3: false, 4: false, 5: false, 6: false, 7: false, 8: true, 12: false, 13: false, 14: false, 15: false, 16: false, 17: false, 18: false, 19: false};
// Outputs the keys: ["2", "8"]
_.keys(_.transform(data, function(r, v, k) { v ? r[k] = 1 : null; }));
// Outputs the keys as integers: [2, 8]
_.map(_.keys(_.transform(data, function(r, v, k) { v ? r[k] = 1 : null; })), _.parseInt)
So basically:
I use this one:
Retrieve all keys with the same value from an object (not only an object with just boolean values) using lodash
function allKeys(obj, value) {
_.keys(_.pick(obj, function (v, k) { return v === value; }));
}
Example:
var o = {a: 3, b: 5, c: 3};
var desiredKeys = allKeys(o, 3);
// => [a, c]