Set all Object keys to false

江枫思渺然 提交于 2019-12-03 23:17:54

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 }

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're not using ES6, here is it's ES5 counterpart.

Object.keys(filter).forEach(function(key, value) {
    return filter[key] = false;
})

hasOwnProperty must be used

```

for(var i in your_object) {
  if (Object.hasOwnProperty.call(your_object, i)) {
    your_object[i] = false;
  }
}

```

A small line of code compatible with all browsers:

for(var i in your_object) 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;
              }, {});

With ES6 features one-liner without mutation:

{
  ...Object.keys(filter).reduce((reduced, key) => ({ ...reduced, [key]: false }), {})
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!