Search code examples
javascriptjsonobjectserialization

How to convert string values into numbers and booleans from an object?


For exmaple if I have a JavaScript Object like,

{
    id: "234",
    name: "shreyas",
    active: "true"
}

How can I convert it to like this

{
    id: 234,
    name: "shreyas",
    active: true
}

Basically removing "" (double quotes) from numbers and booleans.

I managed to remove booleans

let query = JSON.stringify(req.query);
query.replace(/"true"/g, `true`).replace(/"false"/g, `false`);
query = JSON.parse(query)

How can I do the same but with numbers?

What I tried so far:

const nums = query.match(/"\d+"/g);
        
nums?.forEach((num) => {
            
    const newNum = parseInt(num)

    query.replace(`${num}`, `'${newNum}'`);
});

Solution

  • Same issue i have faced with my process.env. So i created parser function for type clear parsed output

    1. we need to pre-declare the false and true values in array
    2. Then return the value inside the loop depend on matched array condition
    3. isNaN(Number(str)) its only accept the pure number. Allowed like this "292" not a233
    4. Additionaly you could create the array from string one,two,three => ["one","two","three"]

    const obj = { id: "234", name: "shreyas", active: "true",arr:"one,two,three" }
    
    
     const clean = (value = '') => {
        let FALSY_VALUES = ['', 'null', 'false', 'undefined'];
        let TRUE_VALUES = ["true"];
        if (!value || FALSY_VALUES.includes(value)) {
            return false;
        }else if (!value || TRUE_VALUES.includes(value)) {
            return true;
        } else if (!isNaN(Number(value))) {
            return Number(value);
        } else if (value.match(',')) {
            return value.split(',').map((a) => a.trim());
        }
        return value;
    };
    
     const parser = (a)=> {
        let env = {};
        for (const k in a) {
            env[k] = clean(a[k]);
        }
        return env;
    };
    
    
    console.log(parser(obj))