Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  9] [ 6]  / answers: 1 / hits: 54540  / 8 Years ago, mon, november 28, 2016, 12:00:00

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?


More From » lodash

 Answers
5

Using lodash, mapValues is a graceful, loop-free way:





filter = {
ID: false,
Name: true,
Role: false,
Sector: true,
Code: false
};

filter = _.mapValues(filter, () => false);


If you want to do this with Underscore.js, there is an equivalent, but with a slightly different name:



filter = _.mapObject(filter, () => false);


In either case, the value of filter will be set to:



{ ID: false, 
Name: false,
Role: false,
Sector: false,
Code: false }

[#59905] Thursday, November 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylie

Total Points: 121
Total Questions: 84
Total Answers: 91

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;