Convert the number or boolean type JSON object from string type to its original in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have a short JSON object like this −

const obj = {"name":"sam","age":"24","isMarried":"false"};

Here, some of the Number and Boolean values, by mistake, have been coerced to String.

Like the age property which was a Number and isMarried property which was a boolean. Our job is to write a function that takes in one such object and correctly changes these incorrect data types with the correct ones.

Example

The code for this will be −

const obj = {
   "name":"sam",
   "age":"24",
   "isMarried":"false"
};
const convertToOriginal = (obj = {}) => {
   const keys = Object.keys(obj);
   for(let i = 0; i < keys.length; i++){
      const key = keys[i];
      const num = parseInt(obj[key], 10);
      const val = obj[key];
      if(num && String(num) === val){
         obj[key] = num;
      }
      else if(val === 'true' || val === 'false'){
         obj[key] = Boolean(val);
      };
   };
};
convertToOriginal(obj);
console.log(obj);

Output

And the output in the console will be −

{ name: 'sam', age: 24, isMarried: true }
raja
Updated on 23-Nov-2020 10:01:48

Advertisements