- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert the number or boolean type JSON object from string type to its original in JavaScript
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 }
Advertisements