Set all Object keys to false

后端 未结 9 1484
执念已碎
执念已碎 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:32

    Well here's a one-liner with vanilla JS:

    Object.keys(filter).forEach(v => filter[v] = false)
    

    It does use an implicit loop with the .forEach() method, but you'd have to loop one way or another (unless you reset by replacing the whole object with a hardcoded default object literal).

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

    If you don't want to modify the array, here's an ES6 alternative that returns a new one:

    Object.fromEntries(Object.keys(filter).map((key) => [key, false]))
    

    Explanation:

    Object.keys returns the object's keys:

    Object.keys({ a: 1, b: 2 }) // returns ["a", "b"]
    

    Then we map the result ["a", "b"] to [key, false]:

    ["a", "b"].map((key) => [key, false]) // returns [['a', false], ['b', false]]
    

    And finally we call Object.fromEntries that maps an array of arrays with the form [key, value] to an Object:

    Object.fromEntries([['a', false], ['b', false]]) // returns { a: false, b: false }
    
    0 讨论(0)
  • 2021-01-03 20:38

    If you're not using ES6, here is its ES5 counterpart.

    Object.keys(filter).forEach(function(key, value) {
        return filter[key] = false;
    })
    
    0 讨论(0)
提交回复
热议问题