Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set all Object keys to false

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?

like image 650
chefcurry7 Avatar asked Nov 28 '16 02:11

chefcurry7


People also ask

How do you set all values of an object to false?

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.

How do you check if all object keys has false value?

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.

How do I remove all properties of an object?

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!

How do you set a key for an object?

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);


1 Answers

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).

like image 85
nnnnnn Avatar answered Oct 23 '22 18:10

nnnnnn