How can I loop through a JSON array in JavaScript and execute a function on each element?

I have been attempting to utilize a JavaScript method called f(x,y) with each element in a JSON array.

Below is an example of my code:

var jsonData = {"a":[1900,1910,1920,1930],"b":[12,19,8,55]}

for (var i=0; jsonData.a.length; i++){
  f(jsonData.a[i],jsonData.b[i])
}

Am I making a mistake with this approach? My code doesn't seem to be functioning as expected..

Answer №1

Your code is causing an infinite loop. Make sure to modify it to

for (let i = 0; i < jsonData.b.length; i++){

Answer №2

Setting a stopping condition for the loop is essential.

Revise the code as follows:

for (var i=0; i < jsonData.a.length; i++){

Instead of:

for (var i=0; jsonData.a.length; i++){

Answer №3

It appears that you have encountered an infinite loop.

You forgot to include a terminating condition in the for loop.

var data = {"x":[10,20,30,40],"y":[5,8,12,18]}

for (var j=0; j < data.x.length; j++){
  calculate(data.x[j],data.y[j])
}

Try adding a termination condition to prevent the infinite loop.

Answer №4

The condition in your for-loop is incorrect. Consider the following correction:

let data = {"x":[10,20,30,40],"y":[4,8,12,16]}

for (let j=0; j < data.x.length; j++){
    process(data.x[j],data.y[j])
}

Answer №5

The condition of your loop is based on the length of "jsonData.a", which will always be considered true since it's a positive integer. A more concise way to write this loop would be using

for (var i=0; i < jsonData.a.length; i++) {...}
, or even better, utilizing the "for in" loop like so: for (var i in jsonData.a) {...}

Answer №6

Here's another approach:

var iterate=Function.prototype.call.bind([].forEach)
var data = {"a":[1900,1910,1920,1930],"b":[12,19,8,55]}
function display(x,y){
    console.log(x+":"+y);
}
iterate(data.a, function(o,i){
    display(o,data.b[i]);
});

Check out this JSFiddle link to experiment: http://jsfiddle.net/sG5st/

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

Utilizing Angular to send a POST request to an external server and showcasing the outcomes within

Currently, I am in the process of integrating my angular application with a payment gateway. However, there are instances where an additional security check is required by the payment processor. Specifically, it involves implementing 3D Secure. Although I ...

Display a toolbar underneath text that has been selected using jQuery

I am attempting to display a toolbar underneath selected text once the user has made a selection. After exploring various Stack Overflow responses, I have devised the following code. My goal is for the toolbar to activate when a user selects text not only ...

Failure when running npm start command in Nest js

After setting up a fresh Nest js on a new EC2 machine, I encountered an error when trying to run it for the first time. The error message indicated that the npm install process failed abruptly without any visible error: ubuntu@ip-172-31-15-190:~/projects/m ...

The harmonious combination of Opera and XMLHttpRequest creates a

Coming from Russia, please excuse any mistakes in my English. I am trying to dynamically load the main page of my website using JavaScript, and I have written this script: <script type="text/javascript"> function httpGet(theUrl) { var xmlHt ...

Unable to utilize the POST method for Ajax requests, experiencing difficulties retrieving values with dd(); in the controller following the use of the GET method, and encountering obstacles when attempting to insert records into the database

Every time I attempt to use the POST method and change the method in the view and routing, I encounter an error stating that "POST method is not supported". When I switch to using the GET method, I'm unable to retrieve values in the controller using d ...

Combining dates with similar conditions in a multi-dimensional PHP array

Here is an array I created: Array ( [0] => Array ( [amount] => 13.31000000 [i] => 1 [created_at] => 2022-10-10 23:21:47 ) [1] => Array ( [amount] => 19.00000 ...

What is the best way to keep selected drop down values after submitting a form?

Is there a way to keep the selected value in a drop-down after submitting a form? I have a form that is submitted using `onchange`, but the issue is that when I select a value from the drop-down, the form gets submitted but the drop-down values remain stuc ...

Creating a redirect button using React Material UI and React Router

I've been exploring how to use Material-UI with React and I'm struggling to figure out the best way to redirect to other pages or components. After reading various articles on different methods of redirection using react-router-dom, I still have ...

JavaScript code for displaying div elements

How can I use script code to show different divs when a button is clicked? This is my current progress: ''' <head> <style> #div-1, #div-2, #div-3{ display: none; width: 100%; padding: ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...

Error: JSON parsing failed due to an expected double-quoted property name in the variable assignment (var json = JSON.parse( xhr.responseText

the JSON file link is provided in the code snippet below SyntaxError: JSON.parse: expected double-quoted property name Javascript: var init = function () { var canv = document.getElementsByTagName("canvas")[0]; var w = canv.clientWidth; var ...

Obtain translations from HTML and JavaScript files

Currently, I am working on a project using Angular 1.6 and incorporating angular-translate for internationalization. The setup for Angular-translate is complete and functioning properly. When I manually include text like: {{'Test' | translate}} ...

Invoke the router function dynamically

I am looking for a way to simplify route registration without manually writing out app.get('/', function (req, res, next) { }); each time. I want to automate this process by passing in a router object like the one below... { path: '&ap ...

What is a method to adjust the height of a paragraph element in AngularJS based on user interaction?

Is there a way to dynamically adjust the height of a paragraph element in Angular when clicking on a "Show More" button? I want the button text to change to "Show Less" and shrink the paragraph back down when clicked again. What would be the most effective ...

Present your JSON object in a visually appealing way using Syntax Highlighter

Having some trouble formatting a JSON object nicely (multiple lines with indentation) using the Alex Gorbatchev plugin: Unfortunately, the JSON object is currently displaying on a single line. I am utilizing the javascript brush. I have set up a code pe ...

Avoid parsing HTML tags when retrieving data from Walmart's open APIs

Is it possible to receive a response from Walmart open APIs without escaped HTML tags? For example, when using the search API, here is a sample response: { "query": "ipod", "sort": "relevance", "responseGroup": "base", "totalResults": 257 ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

jquery mobile and cordova causing issues with refreshing header in collapsible listview

My current project involves developing an app using Cordova and JQuery Mobile 1.4.3 that retrieves data from a webservice. After loading Cordova, I face no issues fetching the data and updating the DOM. The retrieved data is displayed in a collapsible lis ...

Using JavaScript to fetch elements by their ID along with a button

UPDATE: I have corrected the semi-colons, case sensitivity, and brackets in the code. It functions properly if I eliminate the functions after buttonPARTICULAR! Why is that? UPDATE: Issue resolved. My mistake. Apologies!!! :-Z When I simplify it like thi ...

Having issues incorporating Redux into React Native application

Struggling to make a small app work in React Native with Redux. It was functioning fine without Redux, but after attempting to integrate Redux, it now shows a blank white screen and a loading message. I want to avoid using classes and stick to functional p ...