Lets say I have an object
filter: {
\"ID\": false,
\"Name\": true,
\"Role\": false,
\"Sector\": true,
\"Code\": false
}
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).
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 }
If you're not using ES6, here is its ES5 counterpart.
Object.keys(filter).forEach(function(key, value) {
return filter[key] = false;
})