Set all Object keys to false

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

提交回复
热议问题