Lets say I have an object
filter: {
\"ID\": false,
\"Name\": true,
\"Role\": false,
\"Sector\": true,
\"Code\": false
}
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 }
Here's what i would call a neat one-liner solution:
const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
Demo:
const filter = {
'ID': false,
'Name': true,
'Role': false,
'Sector': true,
'Code': false
};
const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
console.log(filtered);
We are basically converting the object into an array using Object.assign()
so we can use the map()
fucntion on it to set each propety value to false, then we convert the array back to an object using the Object.assign()
with the spread operator :)
hasOwnProperty must be used
```
for(var i in your_object) {
if (Object.hasOwnProperty.call(your_object, i)) {
your_object[i] = false;
}
}
```
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;
}, {});
A small line of code compatible with all browsers:
for(var i in your_object) your_object[i] = false;
With ES6 features one-liner without mutation:
{
...Object.keys(filter).reduce((reduced, key) => ({ ...reduced, [key]: false }), {})
}