- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Articles
- C++ Program to Convert String Type Variables into Boolean
- Golang Program to convert string type variables into Boolean
- How to convert string type value to array type in JavaScript?
- MongoDB – Fix “Failed to convert from type String to type Date”?
- Convert Java String Object to Boolean Object
- Convert a String to a double type number in Java
- How to convert a JSON string into a JavaScript object?
- JavaScript Convert a string to boolean
- How to convert from string to date data type in MongoDB?
- How to convert JSON text to JavaScript JSON object?
- How to convert Boolean to String in JavaScript?
- How to convert String to Boolean in JavaScript?
- Java Program to convert a String to a float type Number
- Boolean Type in Java
- Python - Ways to convert string to json object

Advertisements