Get object keys for filtered values

前端 未结 14 1361
傲寒
傲寒 2021-02-05 03:31

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         


        
相关标签:
14条回答
  • 2021-02-05 03:44

    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(":")));
         }
    }
    
    0 讨论(0)
  • 2021-02-05 03:45

    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]
    
    0 讨论(0)
  • 2021-02-05 03:45

    This might be easier

    result = _.chain(obj)
        .map(function(value, key){
            return value?key:false;
        })
        .filter(function(v){
            return v
        })
        .value();
    
    0 讨论(0)
  • 2021-02-05 03:50

    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)
    
    0 讨论(0)
  • 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:

    1. Transform the original object to strip out the false-valued keys
    2. Grab the list of keys from the transformed result
    3. Convert the keys to ints if you need to
    0 讨论(0)
  • 2021-02-05 03:52

    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]
    
    0 讨论(0)
提交回复
热议问题