Search code examples
javascriptlodash

Set all Object keys to false


Lets say I have an object

  filter: {
    "ID": false,
    "Name": true,
    "Role": false,
    "Sector": true,
    "Code": false
  }

I want to set all keys to false (to reset them). What's the best way to do this, I'd like to avoid looping with foreach and stuff. Any neat one liner?


Solution

  • Using lodash, mapValues is a graceful, loop-free way:

    filter = {
        "ID": false,
        "Name": true,
        "Role": false,
        "Sector": true,
        "Code": false
    };
    
    filter = _.mapValues(filter, () => false);
    

    If you want to do this with Underscore.js, there is an equivalent, but with a slightly different name:

    filter = _.mapObject(filter, () => false);
    

    In either case, the value of filter will be set to:

    { ID: false, 
      Name: false, 
      Role: false, 
      Sector: false, 
      Code: false }