If you want to convert non-numerical strings into numbers in JavaScript, you can use the following code:
var obj = {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"};
Object.keys(obj).forEach((itm) => {
if(!Number.isNaN(+obj[itm])) obj[itm] = +obj[itm];
});
console.log(obj);
This script uses the +
operator to convert non-numeric strings to numbers. It checks if the conversion results in a NaN
and handles it accordingly.
If you prefer a more reliable way to check for NaN
, you can use this alternative approach:
var obj = {id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"};
Object.keys(obj).forEach((itm) => {
let conv = +obj[itm];
if(conv == conv) obj[itm] = +obj[itm];
});
console.log(obj);
This method is considered more robust as it relies on checking whether the number is equal to itself or not to determine if it is a NaN
.