How to replace 1 for true in jQuery object

I have an object that is passed to the function as such:

function(config['options']) 

There are certain values ​​here, such as config['options']['property1'] , which are set to 1, which I want to change to true (for example, from 0 to false ) before they are passed to this function.

How can I do this, I cannot figure out using .each()

+4
source share
3 answers

options is an object, so use a for-in loop to iterate over properties:

 for (var key in config.options) { var current = config.options[key]; if (current === 1) { config.options[key] = true; } if (current === 0) { config.options[key] = false; } } 
+8
source

You can use double negation to convert values ​​to boolean. !!1 becomes true and !!0 becomes false

+1
source

This works with double negation:

 var obj = { prop1: 1, prop2: '1', prop3: 0, prop4: '0', prop5: true, prop6: false, prop7: 'test' }, prop, val; for(prop in obj) { val = Number(obj[prop]); !isNaN(val) && (obj[prop] = !!val); } 

Results in (JSON stringified):

 { "prop1": true, "prop2": true, "prop3": false, "prop4": false, "prop5": true, "prop6": false, "prop7": "test" } 
0
source

Source: https://habr.com/ru/post/1483778/


All Articles