Set all Object keys to false

后端 未结 9 1483
执念已碎
执念已碎 2021-01-03 19:50

Lets say I have an object

  filter: {
    \"ID\": false,
    \"Name\": true,
    \"Role\": false,
    \"Sector\": true,
    \"Code\": false
  }
相关标签:
9条回答
  • 2021-01-03 20:20

    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 }
    
    0 讨论(0)
  • 2021-01-03 20:21

    Here's what i would call a neat one-liner solution:

    const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
    

    Demo:

    const filter = {
      'ID': false,
      'Name': true,
      'Role': false,
      'Sector': true,
      'Code': false
    };
    
    const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
    
    console.log(filtered);

    We are basically converting the object into an array using Object.assign() so we can use the map() fucntion on it to set each propety value to false, then we convert the array back to an object using the Object.assign() with the spread operator :)

    0 讨论(0)
  • 2021-01-03 20:24

    hasOwnProperty must be used

    ```

    for(var i in your_object) {
      if (Object.hasOwnProperty.call(your_object, i)) {
        your_object[i] = false;
      }
    }
    

    ```

    0 讨论(0)
  • 2021-01-03 20:26

    In case you are dealing with 'scope' variables, this might be a better solution.

    Object.keys(filter).reduce(function(accObj, parseObj) {
                    accObj[parseObj] = false;
                    return accObj;
                  }, {});
    
    0 讨论(0)
  • 2021-01-03 20:28

    A small line of code compatible with all browsers:

    for(var i in your_object) your_object[i] = false;
    
    0 讨论(0)
  • 2021-01-03 20:31

    With ES6 features one-liner without mutation:

    {
      ...Object.keys(filter).reduce((reduced, key) => ({ ...reduced, [key]: false }), {})
    }
    
    0 讨论(0)
提交回复
热议问题