Traversing through data stored in a variable (JSON object)

Does anyone know how to loop through JSON data inside a variable? For example:

var data = {

                        $.each(data, function(i, item) {
                            console.log(data[i].PageName);
                        });​

                        labels: [dateLoop],
                        datasets: [{

                        }]
                };

The code above didn't work for me. I need to loop inside that variable because I have filters for buyers and date ranges. For instance, if I select 3 buyers and a date range from January 2016 to May 2016, the data will show each buyer's values within that date range. Here is an example of the JSON data:

data [Buyer 1] : ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"];
data [Buyer 2] : ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"];

I'm trying to figure out how to loop inside the variable. Apologies for my poor language.

To provide a clearer explanation, let's say I choose 2 buyers - Buyer A (Json["data"][0]) and Buyer B (Json["data"][1]). Each buyer has values ordered by month. If I pick January and May, it should show values like "222," "555." The code could look something like this:

var data = {

  labels: [dateLoop], #ignore this

  datasets: [{ label :  (Json["data"][0])

                           fillColor: "rgba(220,220,220,0.2)",

strokeColor: "rgba(220,220,220,1)",

pointColor: "rgba(220,220,220,1)",

pointStrokeColor: "#fff",

pointHighlightFill: "#fff",

pointHighlightStroke: "rgba(220,220,220,1)",

data: [(value orderby month in Json["data"][0]]       

  },

{ label :  (Json["data"][1])

                           fillColor: "rgba(220,220,220,0.2)",

strokeColor: "rgba(220,220,220,1)",

pointColor: "rgba(220,220,220,1)",

pointStrokeColor: "#fff",

pointHighlightFill: "#fff",

pointHighlightStroke: "rgba(220,220,220,1)",

data: [(value orderby month in Json["data"][1]]       

  }

]

    };

That's what I'm aiming for, but using 'each' is causing errors. :/

Answer №1

Here's a helpful tip: To access the keys and values inside an array, you can use two loops.

var data = {
        'Buyer 1': ["167404", "129770", "113598", "127301", "156868", "634789", "242188", "166312", "169418"],
        'Buyer 2': ["9580", "22250", "3500", "5558", "254556", "268500", "77750", "69850", "55"]
    }
for(var key in data) {
    for (var x in data[key]) {
        console.log(data[key][x]);
    }
}

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

Vue allows you to easily generate child div elements within a parent

Having some issues creating a child div with Vue. The code is being placed correctly, but it's being stored as an array. <template> <div class="containers" v-bind:style="{ backgroundColor: pageStyle.backgroundColor, paddingLeft:'5%& ...

What steps do I need to take to ensure my TypeScript module in npm can be easily used in a

I recently developed a module that captures keypressed input on a document to detect events from a physical barcode reader acting as a keyboard. You can find the source code here: https://github.com/tii-bruno/physical-barcode-reader-observer The npm mod ...

Executing a backend C# function from a front end Javascript function in ASP.NET: A Step-by-Step Guide

As part of my current unpaid internship in C# and Asp.net, my employer has assigned me the task of implementing a JavaScript function to prompt the user for confirmation before deleting a record from the database. After conducting thorough research, I suc ...

Exploring the shine: implementing reflection in THREE.js

Is there a way to achieve a material that reflects other shapes from the scene? I attempted to use the reflectivity property but had no success in seeing any reflection. I found an example demonstrating this effect It seems like non-standard materials we ...

Converting JSON to a List in C# using a console application

Issue Encountered an error while deserializing JSON object into the appropriate type. The current JSON object does not match the required JSON array format for deserialization. To resolve this issue, either modify the JSON to fit a JSON array structure ...

Tips on bringing data from a php file into a javascript variable

I'm faced with a challenge where I need to extract data from a MySQL database using a PHP file and then store that data in a JavaScript array for plotting purposes with jQuery's flot library. Has anyone encountered a similar situation and found a ...

Failure [ERR_STREAM_WRITE_AFTER_END]: writing past the endpoint [npm-request using socket.io]

My server has a socket server running, and on my laptop, I have a socket.io-client service. When both are turned on, they establish a connection. When other users request information from my server, the server sends that request to my laptop via a socket. ...

What are some creative ways to enhance closePath() in canvas styling?

Currently, I am faced with the challenge of styling the closePath() function on my canvas. Specifically, I would like to apply different stroke styles to each line segment. For now, let's focus on changing colors for each line. In the example below, y ...

What could be the reason why the @media print selector is not showing the correct format when I try to print?

When I click the print button, the text is supposed to display in four columns in the print dialog, but it appears as paragraphs instead. This is my script code where there is a click event for the print button. When I click on it, the print dialog pop ...

Could not find reference to Google (error occurred following ajax request)

I encountered an error message when attempting to use the Google Map after making an ajax call. ReferenceError: google is not defined The issue arises when I include the link "<script type="text/javascript" src="http://maps.google.com/maps/api/js?sen ...

Is it possible to run a local file on a localhost server in Sublime Text 3 with the help of the SideBar

I am attempting to host my index.html file on a localhost server in order to utilize an angular routing directive. Despite following the steps, I am encountering issues. //sidebarenchancements.json { "file:///C:/Users/Jdog/Desktop/projects/Calibre/soci ...

What is the method for incorporating an upward arrow into a select element, while also including a downward arrow, in order to navigate through options exclusively with

I have a select element that I have styled with up and down arrows. However, I am seeking assistance to navigate the options dropdown solely using these arrows and hide the dropdown list. Here is the HTML: <div class="select_wrap"> <d ...

The call function in Tween.js fails to execute after adding an EventListener

I encountered an issue while using tween.0.6.2. The following code snippet (borrowed from the tween.js Getting Started page and slightly simplified) works perfectly: createjs.Tween.get(circle) .to({x: 400}, 1000, createjs.Ease.getPowInOut ...

Using Python to convert JSON to a JSON array and add the date at the start

I am working with the following JSON data: [{"UGC_TECH_PLATEFORME": "youtube", "UGC_TECH_ID": "UCu93VC-rD_TolBF4Pe5yz_Q"}] My desired result is: [{"2020-09-23":{"UGC_TECH_PLATEFORME": "youtu ...

Having trouble adding state values to an object

I have a specific state set up in my class: this.state = { inputValue: "", todos: [] } My issue lies within an arrow function where I am attempting to use setState to transfer the value of inputValue into todos. this.setState({ inputValue: & ...

Steps for adding a div after a specified number

To display the following div after getting a value greater than or equal to the specified value and retrieving it through ajax: 1. How can I show the below div with the given value? .mainbox{ width:auto; height:auto; padding:20px; background:#f00; } .i ...

Collecting information from form submissions, accessing data from the database, and displaying the results

I am currently working on a project using nodejs, express, and mongodb within the cloud9 IDE. My goal is to create a page with a form that allows users to input data, search for corresponding information in the database, and display that data on the same ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

Launching the ngx Modal following an Angular HTTP request

Trying to trigger the opening of a modal window from an Angular application after making an HTTP call can be tricky. Below is the content of app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/pla ...

What is the best way to merge two fetch requests in order to gather the required data?

If I want to create a website with details about movies, one crucial aspect is getting information on genres. However, there's a challenge in the main data request where genres are represented by IDs. I need to execute another query that includes thes ...