问题
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?
回答1:
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 }
回答2:
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).
回答3:
If you're not using ES6, here is it's ES5 counterpart.
Object.keys(filter).forEach(function(key, value) {
return filter[key] = false;
})
回答4:
hasOwnProperty must be used
```
for(var i in your_object) {
if (Object.hasOwnProperty.call(your_object, i)) {
your_object[i] = false;
}
}
```
回答5:
A small line of code compatible with all browsers:
for(var i in your_object) your_object[i] = false;
回答6:
In case you are dealing with 'scope' variables, this might be a better solution.
Object.keys(filter).reduce(function(accObj, parseObj) {
accObj[parseObj] = false;
return accObj;
}, {});
回答7:
With ES6 features one-liner without mutation:
{
...Object.keys(filter).reduce((reduced, key) => ({ ...reduced, [key]: false }), {})
}
来源:https://stackoverflow.com/questions/40836239/set-all-object-keys-to-false