Transform all the string data to integers in the JSON reply

Apologies for the basic question:

This is the response I'm receiving:

{id: "bitcoin", name: "Bitcoin", symbol: "BTC", rank: "1", price_usd: "15487.0"}

I want to convert rank: "1", price_usd: "15487.0" to rank: 1, price_usd: 15487.0

The reason behind this conversion is that my table sorts alphanumeric instead of numeric values.

Could someone please advise on how to make this adjustment?

Answer №1

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.

Answer №2

Utilizing the JSON.parse reviver method allows for conversion and filtering of values:

data = '{"id":"bitcoin","name":"Bitcoin","symbol":"BTC","rank":"1","price_usd":"15487.0"}'

object = JSON.parse(data, (key, value) => isNaN(+value) ? value : +value)

console.log(object)

Answer №3

To ensure proper sorting in MySQL database, consider setting the column rank as an integer and price_usd as a decimal.

If you prefer to convert the data on the client side, you can use the following approach:

for(var key in data) {
  if(key === 'price_usd') {
    data[key] = parseFloat(data[key]);
  }
  // Handle conversion for 'rank' as well
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you experiencing issues with the map displaying inaccurate latitude and longitude when clicking on a specific point?

I've successfully created a simple polyline on Google Maps and attached a click event listener to it. However, I'm encountering an issue where clicking on the line provides me with latitude and longitude coordinates that point to Canada, even th ...

Create a new function in jQuery validation

Currently, I am in the process of validating my form using the jQuery validation plugin. However, I have encountered a problem that I need help with and also have a specific question regarding my implementation. View my code on fiddle. The issue at han ...

A guide to displaying JSON data in a line chart with Swift

I'm currently in the process of designing an iOS app that presents JSON data in a line chart format. Here's a snippet of the JSON data I'm working with: { TH_5min: [ { Data: "2019-02-23T00:00:00", Time: "11:00:00", XTP_A: 10.5, XHP_A: 11. ...

How can you pause a YouTube video using jQuery?

My custom jQuery slider consists of three panels that slide smoothly by adjusting their left CSS values. Everything works perfectly, except for one issue - I have a YouTube video embedded in one of the slides, and it continues playing even when the slide i ...

The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can ...

Give a radio button some class

<input id="radio1" type="radio" name="rgroup" value="1" > <label for="radio1"><span><span></span></span>1</label> <input id="radio2" type="radio" name="rgroup" value="2" > <label for="radio2"><span ...

Exploiting jQuery UI in a Web Browser Bookmarklet

When using CoffeeScript, even though the code is very similar to JavaScript: tabs_html = "<div id='nm-container'><ul><li><a href='#tabs-1'>Guidelines</a></li><li><a href='#tabs-2'& ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

Issues with executing basic unit test in Angular Js

THE ISSUE: In an attempt to create unit tests for my Angular application, I set up a basic test app and wrote a simple unit test. However, the test is not functioning as expected. APPLICATION CODE: var app = angular.module( 'myApp', [] ); app ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

Tips for incorporating unique styles to a component in ReactJS

Struggling to apply unique styles to a React Next.js component? Below is the code snippet for a button component: import styles from "./button.module.css"; const Button = props =>{ return( <div> <button className={styles.button}>{ ...

Performing multiple http requests in a loop and combining the retrieved data using AngularJS

I am currently working with a piece of source code that looks like this: var projectPromises = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456'); $q.all([projectPromises]).then(function(data) { console.log(data); ...

Using JQUERY to store the ID of a div along with its checked value in a multidimensional array

I am looking to create an array that stores the ID of a div and the checked value. Check out this FIDDLE for reference For example, if I check samsung and lenovo under brands, and select 4gb for RAM, the array should be: array[ ] = ["brands" ...

Is there a more effective approach to designing a login screen?

I am just starting out with angular js and this login page is my first step. I have created a basic login form, but when I click on the login() button, the form() does not get submitted and it keeps showing an error message saying "invalid username and pas ...

Can JavaScript be used to identify if the current browser is the default one being used?

It would be incredibly helpful for my application to determine if the current browser is set as the default browser. Is it feasible, utilizing JavaScript, to ascertain whether the browser in which my page is open is the default browser (i.e. the browser t ...

Need to remove bold formatting? Try this compact WYSIWYG editor!

Hello Stack Overflow community, I discovered a method called str.bold() that wraps text in <b></b> tags, which is perfect for a small WYSIWYG editor (I understand there are many open source solutions available, but I wanted to learn by creatin ...

What causes the disparity in the functionality of getServerSideProps between index.js and [id].js in NextJS?

Exploring NextJS and React as part of my e-commerce site development journey has been exciting. However, I encountered a roadblock when trying to connect to an external database that requires real-time updates, making getStaticProps unsuitable for my needs ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

Leveraging NetSuite's Advanced PDF (Freemarker) functionality to extract JSON data from records and showcase the

Utilize the NetSuite Advanced PDF to source a JSON array of objects from a custom field on an Item fulfillment record. Iterate through and display the values on the PDF. Unfortunately, assigning the JSON does not seem to be effective. <#assign array = ...