Converting JSON arrays to integers from strings in JavaScript: A step-by-step guide

When my application receives a Json string from the server (written in Java), I am faced with an issue when retrieving the data in JavaScript. The current format of the data looks like this:

var data = [{"value":"3","label": "17 hr"},
 {"value":"2", "label":"18 hr"},
 {"value":"1", "label":"19 hr"}]
 }]

What I actually need is:

var data = [{"value": 3, "label": "17 hr"},
 {"value": 2, "label": "18 hr"},
 {"value": 1, "label": "19 hr"}]
 }]

The problem lies in the fact that the values are retrieved as strings instead of integers. How can I modify the retrieval process to get them as integers? What would be the most efficient way to achieve this?

Answer №1

const info =  [{"value":"3","label":"17 hr"},
 {"value":"2","label":"18 hr"},
 {"value":"1","label":"19 hr"}]

// Keep original data intact by creating a new parsedData array
const parsedInfo = info.map(function(entry) {
  return {
    value: parseInt(entry.value, 10),
    label: entry.label
  };
});

// Mutate the original data if changes are acceptable
info.forEach(function(entry) {
  entry.value = parseInt(entry.value, 10)
});

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

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Sending an array of strings to an Oracle query with jOOQ

Currently, I am utilizing the jOOQ code generator to invoke a query from an Oracle package. Within this query, one of the parameters is a String array. The initial problem arises when the code generator designates the type of the parameter as Object. The ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

What is the best way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

Is there a way to extract data from the Redux state in a React component?

Seeking assistance with making an API request from Redux, followed by saving the data in my React state (arrdata). Although the API call is successful, I am facing challenges updating the App.js state based on the Redux API call. Any suggestions or insig ...

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

Issue: The 'name' module is experiencing a production error due to java.lang.NullPointerException

My Java project is currently being run in IntelliJ 14.1.1 with the play framework. Strangely enough, I am encountering issues with compiling the code within IntelliJ, even though everything runs smoothly in the play environment. Whenever I attempt to compi ...

When trying to use npm install, the process is being interrupted by receiving both 304 and 404

Whenever I execute the npm install command, my console floods with this: npm http fetch GET 304 http://registry.npmjs.org/is-arrayish 60ms (from cache) npm http fetch GET 304 http://registry.npmjs.org/spdx-license-ids 67ms (from cache) npm http fetch GET ...

The promise catch method does not handle JSON parsing correctly

Utilizing Angular's Http to interact with my API has been successful for handling responses with a status of 200. The data is parsed correctly and outputted as expected within the first .then() block. However, when encountering an error with a status ...

Adding the Authorization header in an Ajax request within ExtJS can be easily done by including the

I've been struggling to upload a file using ExtJS and web API. The issue I'm facing is that when trying to send an authorization header to the server, it always returns as null. I even attempted to include the header in the XHR request within the ...

Updating column names in Laravel web API creation process

I am facing an issue while creating a web API using Laravel. Whenever I retrieve data from a query, it returns the data with the actual table column names. For example, if I fetch data from the user table, it looks like this: { ["first_name":"John", "la ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

applying attributes to an element

Can you tell me why the addClass method is adding the class 'foo' to both the div and p element in the code snippet below? $('<div/>').after('<p></p>').addClass('foo') .filter('p').attr ...

What is the process for executing Selenium IDE scripts in Selenium RC?

As a newcomer to using the selenium testing tool, I am seeking guidance on running selenium IDE scripts within selenium RC. I would greatly appreciate examples and screenshots to help me better understand the process. ...

Two liquid level divs within a container with a set height

I hesitated to ask this question at first because it seemed trivial, but after spending over 3 hours searching on stackoverflow and Google, I decided to give it a shot. The issue I'm facing can be found here: http://jsfiddle.net/RVPkm/7/ In the init ...

Error: Module not located or Image unable to load in React JS

Here is the structure of my project : src -assets fut.png -components -admin_dashboard Sidebar.js -App.js -pages Dashboard.js I encountered an issue trying to load the image fut.png from the file Sidebar.js. Even after attempting ...

``In JavaScript, the ternary conditional operator is a useful

I am looking to implement the following logic using a JavaScript ternary operation. Do you think it's feasible? condition1 ? console.log("condition1 pass") : condition2 ? console.log("condition2 pass") : console.log("It is different"); ...

Can you tell me why the outputs of these two codes are different when I ran them?

Recently I was tackling a challenge in JavaScript where the task involved dividing the number of volunteers by the number of neighborhoods. To achieve this, I decided to use the array method .length which would return the length of an array. However, what ...

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...