Transform a JSON array into a JavaScript array

var jsonData = JSON.parse(pump_array);
var name_array = [];
var data_array = [];
for(var i=0;i<jsonData.pumps.length;i++)
{
data_array.push(data_array, pump_array.pumps[i].volume);
name_array.push(name_array, pump_array.pumps[i].iName);}

This snippet represents my JavaScript code where I extract specific data from the given JSON object to plot it on a graph using chart.js.

var pump_array = {
"pumps":[
    {
  "id": 1,
  "isPrimed":true,
  "iName": "Whiskey",
  "volume": 850,
  "debug": "Test"
    },

    {
  "id": 2,
  "isPrimed":true,
  "iName": "Vodka",
  "volume": 900,
  "debug": "Test"
    }
  ]
}

Answer №1

It appears there are multiple issues to address here. Firstly, the use of JSON.parse is unnecessary as you're applying it to a Javascript object rather than a string.

Secondly, in these two lines, there seems to be an extra variable being included:

data_array.push(data_array, pump_array.pumps[i].volume);
name_array.push(name_array, pump_array.pumps[i].iName);}

The corrected version should look like this:

data_array.push(pump_array.pumps[i].volume);
name_array.push(pump_array.pumps[i].iName);}

Even after addressing these issues, the current data structure is not optimal:

name_array; //=> ["Whiskey", "Vodka"]
data_array; //=> [850, 900]

Rather than having separate arrays requiring shared indices, consider restructuring the data like this:

pump_array.pumps.reduce(function(accumulatedData, pump) {
    accumulatedData[pump.iName] = pump.volume; 
    return accumulatedData;
}, {});
//=> {Whiskey: 850, Vodka: 900}

This revised data structure is more effective and organized in my opinion.

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

Tips for switching images in a grid using jQuery

I have implemented an image grid using flexbox on a website I am developing. The grid consists of 8 boxes, and my goal is to randomly select one box every 2 seconds and assign it one of 12 random images. My strategy involves creating an array containing UR ...

Implement a feature in JS/HTML where clicking on a button shifts a specific section of a row from one table to another while simultaneously deleting the remaining

I am facing an issue with two tables - addFriends and existingFriends. The addFriends table contains a button in the fourth column, which, upon clicking, should delete the corresponding row from that table and add it to the existingFriends table. Currentl ...

Exploring array elements in Java for various orientations

In my project, I am working on stitching together multiple bitmaps from a layout array to create a larger guide bitmap. When I rotate the entire bitmap, my solution is to re-stitch it while adjusting the array to account for this rotation. The order of the ...

Creating a novel data structure by combining two arrays of hashes

I have a task at hand where I need to merge two arrays of hashes into a new data structure. This new structure will be a hash reference, containing an array of hashes for each key. Here are the two structures that I am working with - obtained by using sel ...

Bringing to life in Vue.js

I am a beginner with Vue.js and I have been attempting to integrate Materialize into my project. I have experimented with various plugins such as vue-materialize (https://github.com/paulpflug/vue-materialize) and vue-material-components (https://www.npmjs. ...

retrieveStyle() rooted framework Category

I have implemented a customized Native Base style theme following the instructions in this link. Imports: import material from './native-base-theme/variables/material'; import getTheme from './native-base-theme/components'; return ( ...

Obtain the default/initial argument type of typescript for extension purposes

Currently, I am in the process of developing code that automatically generates type hints based on function calls related to GraphQL Nexus tasks. In one of its functions, it requires an anonymous type constructed from the attributes generated automaticall ...

Enhancing data rendering by incorporating extra verifications through the logical AND operator to prevent crashes upon page refresh

Upon refreshing the page, my app crashed. The issue stemmed from the page loading faster than my data, prompting me to include additional checks using the logical AND operator. While effective in preventing crashes, this approach seems laborious and begs t ...

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

Make sure that the equal sign is never utilized at the beginning of a form input field

Seeking a method to prevent the use of the "=" character in any input field within a form. <form> <input name="email" type="email" placeholder="Email" required=""> <input name="last name" type="text" placeholder="Last Name"> ...

Using Three.js to incorporate an external JavaScript file into an HTML document

Currently experimenting with three.js and successfully rendered a 3D cube using HTML. Here's a snippet of the HTML code: <div id="render" class="center-block"> <script> // JavaScript code for rendering the 3D cube goes here </script&g ...

Simulating npm package with varied outputs

In my testing process, I am attempting to simulate the behavior of an npm package. Specifically, I want to create a scenario where the package returns a Promise that resolves to true in one test and rejects with an error in another. To achieve this, I hav ...

When a frameset is clicked on

Apologies for my limited English skills, as I am a novice in JavaScript. Seeking assistance! I currently have a website with a frameset consisting of left, top, and main sections. My goal is to incorporate a chat feature with a user list in the left frame ...

What are the best ways to suggest modifications to RFC(s) regarding JSON in order to incorporate feedback and comments?

After coming across several RFCs related to JSON, I began pondering the best approach for suggesting a modification to the grammar or parser sections to introduce support for comments. JSON currently does not officially allow comments, but I believe ther ...

What is the best way to retrieve properties from a different module in JavaScript?

I have a module named ProgressIndicator: ... export default class ProgressIndicator { constructor() { ... const indicatorGeometry = new THREE.PlaneGeometry(2, 2, 1, 1) const indicatorMaterial = new THREE.ShaderMate ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...

Nodeca's js-yaml now allows appending '>-' to handle extended strings with ease

With the npm package js-yaml, I am attempting to work with a .yaml file. Although I can manipulate it successfully, I encounter an issue when trying to save a long string. Actual: abvs_adas: >- c2Rhc2Rhc2Rhc2Rhc2RwaW9qbGtkZ2hqbGtzZGhmZ2psaGFzamh ...

Unusual behavior observed when declaring arrays

Here is a simple function scenario: DoRead(double *writeArray){ //GblOutData represents an array of 80 elements, each being 1 writeArray=GblOutData; //prints out the element at index 5 printf("%f",writeArray[5]); return 0; } What occu ...

How can we ensure that multiple forms are validated when submitting one form in AngularJS?

Is there a way to validate two forms on the same page (address1 and address2) using AngularJS when the button on one of the forms is clicked? ` ...

Exploring the topic of nested Firestore listeners and effectively managing the process of unsubscribing

I am interested in implementing a nested listener structure similar to the following: snapshotListeners() { firestore() .collectionGroup() .where() .onSnapshot({ error: //Handle error next: firstSnapshot => { first ...