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

Viewed 149

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}'`);
});
2 Answers

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))

My code is not perfect, but I hope it can help a little though

let blah = {
    id: "234",
    age: "44",
    name: "shreyas",
    active: "true",
    isActive: "false"
};

console.log(converting(blah));

function converting(obj) {
  let keys = Object.keys(obj);

  for (let key of keys) {
    // convert to int
    if (parseInt(obj[key])) {
      obj[key] = parseInt(obj[key]);
    }
    // convert to boolean
    if (String(obj[key]).toLocaleLowerCase() === 'true' ||
    String(obj[key]).toLocaleLowerCase() === 'false') {
      obj[key] = String(obj[key]).toLocaleLowerCase() === 'true';
    }
  }

  return obj;
}

Related