Tips for transferring JSON values into an array

What is the best way to convert JSON values into an array?

I am using an AJAX request to fetch the JSON data.

$.getJSON( "data/data.json", function( data ) {         
        var obj=data["DataContainer"]["profit"];
        for(i in obj){
            var temp=[];
            temp.push(obj[i].current);
            temp.push(obj[i].target);
            data3.push(temp);
        }   
        JSON.stringify(data3).replace(/\"/g, "");
        console.log(JSON.stringify(data3).replace(/\"/g, ""));
});

The JSON data:

{
  "DataContainer": {
    "profit": [
      {
        "current": "60","target": "19"
      },
      {
        "current": "55","target": "19"
      },
      {
        "current": "55","target": "19"
      },
      {
        "current": "55","target": "19"
      },
      {
        "current": "55","target": "19"
      },
      {
        "current": "55","target": "19"
      }
    ]
  }
}

The output of the console.log will be:

[[60,19],[55,19],[55,19],[55,19],[55,19],[55,19]]

Now I want to pass these values from console.log to a new variable:

var rows = [["Current profit","Target profit"]],
            data3 = [[27, 19],[22,19],[35, 19],[23,19],[19, 19],[17,19]];

The expected results should be:

var rows = [["Current profit","Target profit"]],
            data3 = [[60,19],[55,19],[55,19],[55,19],[55,19],[55,19]];

Any assistance on this matter would be greatly appreciated. Thank you.

To better comprehend the issue, I have shared my code on Jsfiddle (since I cannot load the JSON from GitHub)

Please refer to this JSFIDDLE

Answer №1

To convert strings to numbers in the data3 array, you can utilize the parseInt() method:


for(i in obj){
    var temporary=[];
    temporary.push(parseInt(obj[i].current, 10));
    temporary.push(parseInt(obj[i].target, 10));
    data3.push(temporary);
}

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

Checking an array for any empty values through user input

evaluate::no_user() this function will verify an array for 'missing' values - NULL, FALSE, 0, or ' ' /*verify*/ class evaluate { static function no_user($inputArray) { return (int)!in_array('',$inputArray) ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Using AngularJs to Implement ng-class on an Input Element within a custom Directive

I've been working on improving our directive. Previously, it consisted of a single input element with type='submit' and class "btn", and the directive had replace set to "true". I have now updated the template for this directive as shown bel ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

Having difficulty properly trimming and highlighting identical words in two strings

My application includes a SearchBar that suggests words starting with the input from the SearchBar. For example: If I type skrillex in the SearchBar, the suggestions would be: skrillex skrillex kyoto skrillex cinema skrillex bangarang skrillex live I wa ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

The functionality of PHP in relation to the jQuery post feature seems to be malfunction

After developing the JavaScript functionality for this contact form, below is the HTML structure without any CSS styling included: <!-- Contact Form --> <div class="cws-widget"> <div class="widget-title" style="color:#fec20b;">S ...

It is not feasible to document JSON within a URL

For my Rest API, I am working on enabling the retrieval of data within a specific bounding box. Since the bounding box requires four coordinates, I intend to structure the GET requests in a way that allows them to accept the bounding box as JSON. This mean ...

Passing image source from parent component to child component in Vue.js

I encountered an issue where I stored the image file name in a variable within the parent component and passed it to the child component using props. However, despite this setup, the child element is not displaying the image as expected. Here is the data ...

Accessing a file's source using the Box.net API and downloading the file contents

Recently, I've been busy working on a Web Application project (for fun) that focuses on editing files stored in the cloud. I'm utilizing the box.net API for this task, but I've come across a challenge - obtaining the source code of files. Un ...

Learn the technique for showcasing numerous markers on Google Maps, each equipped with its own individualized info windows

https://i.sstatic.net/1tTUD.png // map center var center = new google.maps.LatLng(2.855262784366583, 105.4302978515625); function initialize() { var mapOptions = { center: center, zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP }; // Create a < ...

Tips for updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

Share the name of the Quasar component with the Vue 3 render function

I'm struggling to dynamically create a Vue 3 app with different components specified by name, such as "div", "button", or Quasar's "q-btn". When I try to pass the latter to Vue's render function Vue.h, I encounter difficulties. <html> ...

Do the HTML elements containing tracks in Twilio Programmable Video need to be detached before removing them, or is simply removing them enough?

When using Vue.js, I maintain a list of all Participants in an array called participants. Initially, when a Participant joins, they are added to this array. The v-for directive is then used to generate the container for the Participant's media. Once t ...

Implementing Facebook conversion tracking when there is no distinct 'Thank you' page can be done by utilizing the onclick event

Currently working on incorporating Facebook conversion tracking into a Facebook Tab. To see the page, visit this link. The issue I'm facing is that a separate page does not load after the form has been submitted. Is there a way to execute a section of ...

What is the best way to handle parsing a JSON in Java that contains a property that could be either a String or an Object?

My backend is using mongodb and nodejs to create an API. The API server will return the same user object in different formats, for example: // curl http://localhost/users/5382f2949a24ed95b44dc04f { id: "5382f2949a24ed95b44dc04f", "name": "jack", "group": ...

Issue with alert dismissal button not visible

I am dynamically updating the alert message: <div id="alert" hidden="hidden"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> </div> $('#alert').addClass("alert alert-dan ...

How can I modify the date format using the Google Ajax Feed API?

Currently, I am utilizing Google's AJAX Feed API to pull data from an RSS feed. However, I am curious about how to modify the date format. The current format fed by "datePublished" appears as follows: Sun, 29 Jan 2012 23:37:38 -0800 Is there a way t ...

Storing user credentials locally on PhoneGap for Android and sending them as JSON for notifications

Having previously developed simple apps using phonegap for android, I am now working on a project that requires status bar notifications from a background service per user. Utilizing the phonegap backgroundservice plugin, I have been successful in receivin ...