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?
To set all properties of an Object to false , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array and set each of the object's properties to a value of false . Copied! const obj = { one: true, two: false, three: true, }; Object.
To check if all of the values in an object are equal to false , use the Object. values() method to get an array of the object's values and call the every() method on the array, comparing each value to false and returning the result.
Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!
Object keys can be dynamically assigned in ES6 by placing an expression in square brackets. Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console. log(object);
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With