Operating in loops and retrieving data from JSON, then adding them to collections

In a JSON file, there is an object called "lineChart" with multiple keys and values. Each value contains various other objects. Here's an example:

"lineChart": {
    "Fri Jul 28, 2017": {
        "renewalFee_EUR": 1165,
        "extensionFee_EUR": 0,
        "renewalFee_USD": 5941.5,
        "extensionFee_USD": 0,
        "processingFee_USD": 25,
        "expressFee_USD": 0,
        "urgentFee_USD": 0,
        "latePayPenalty_USD": 0,
        "fxRate": 5.1,
        "subTotal_USD": 5966.5
    },
    "Tue Aug 1, 2017": {
        "renewalFee_EUR": 1165,
        "extensionFee_EUR": 0,
        "renewalFee_USD": 2411.55,
        "extensionFee_USD": 0,
        "processingFee_USD": 25,
        "expressFee_USD": 0,
        "urgentFee_USD": 0,
        "latePayPenalty_USD": 0,
        "fxRate": 2.07,
        "subTotal_USD": 2436.55
    }
}

I have managed to extract the key values like Fri Jul 28, 2017 and store them in an Array for chart data representation.

var caLine = vm.graph.lineChart; 

lineLabelArr = [];

for (var prop in caLine) {
    if (caLine.hasOwnProperty(prop)) {
        lineLabelArr.push(prop)
    }
}

vm.labels = lineLabelArr;

Now, I want to specifically access the data under the subTotal_USD key in the JSON file and display it on my chart.

Question

How can I iterate through each property in the lineChart object, retrieve the values from the subTotal_USD key, and save them in an Array for chart data usage? I feel like I might be overcomplicating things.

Answer №1

If you already have an array of keys, there are various methods like forEach, map, reduce, etc., that you can use to loop over them.

To create a new array from the existing array of keys, you can utilize the map method:

const lineChart = {"Fri Jul 28, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:5941.5,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:5.1,subTotal_USD:5966.5},"Tue Aug 1, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:2411.55,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:2.07,subTotal_USD:2436.55}};

const lineLabelArr = [];

for (var prop in lineChart) {
    if (lineChart.hasOwnProperty(prop)) {
        lineLabelArr.push(prop)
    }
}

console.log(
  lineLabelArr.map(key => lineChart[key].subTotal_USD)
);

There are multiple ways to iterate over an object's keys. Personally, I prefer doing it within a single loop:

const lineChart = {"Fri Jul 28, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:5941.5,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:5.1,subTotal_USD:5966.5},"Tue Aug 1, 2017":{renewalFee_EUR:1165,extensionFee_EUR:0,renewalFee_USD:2411.55,extensionFee_USD:0,processingFee_USD:25,expressFee_USD:0,urgentFee_USD:0,latePayPenalty_USD:0,fxRate:2.07,subTotal_USD:2436.55}};

const labels = [];
const subTotals = [];

Object.keys(lineChart).forEach(day => {
  const dayData = lineChart[day];
  
  labels.push(day);
  subTotals.push(dayData.subTotal_USD);
});

console.log("Labels:", labels);
console.log("subTotals:", subTotals);

Answer №2

iterating through the caLine array to retrieve subTotal_USD values for each data object.

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

When incorporating sequelize's belongsTo and hasOne methods, you may encounter an issue where the call stack size surpass

Within my Discussion entity, I have: Discussion.hasOne(sequelize.import('./sound'), { relations: false }) While in the Sound entity, the relationship is defined as: Sound.belongsTo(sequelize.import('./discussion')) To load t ...

Is it advisable to display my JSON data in the console before utilizing Firebase $save or $add?

After spending hours trying to debug a Firebase rule issue, I'm wondering if there is an easier solution available. The challenge I'm facing is that when I save my firebaseObject using $save (or create it with $add), I encounter a permission den ...

Expanding the filtering capabilities in AngularJS with additional selection options

I'm working with a repeater and implementing a filter to query the items, like this: ng-repeat="item in items | filter:query" Now, I want to incorporate a select option as an additional filter. Any ideas on how to integrate this with the existing fi ...

Unraveling the parent data from wp_get_themes in WordPress

Using the function wp_get_themes, I am able to retrieve data like this: 'customizr-child' => WP_Theme::__set_state(array( 'theme_root' => 'C:\\xampp\\htdocs\\wordpress/wp-content/them ...

What is the extent of a variable's visibility within an ng-repeat directive in AngularJS?

Can you tell me the scope of the showDetails variable? Does it only apply to its own li or does it impact all the li elements in the ul? For the full code, please visit http://jsfiddle.net/asmKj/ ul class="procedures" ng-app ng-controller="sample"> < ...

Bootstrap tab toggle feature

I'm currently facing an issue with Bootstrap's tab component. I need help figuring out how to hide a lorem ipsum section and show a hidden div when a specific tab is clicked, and then revert the changes when a different tab is selected. $(func ...

Skipping element submission in AngularJS when the element is hidden

I am facing an issue with a dropdown list containing enum values. Even when the dropdownlist is hidden using ng-show, the value is still being submitted as ''. As a result, I am encountering the following error: org.codehaus.jackson.map.JsonMapp ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

Guidance on sharing an image on Twitter using Node.js

Every time I attempt to upload a PNG image to the Twit library in Node, an error arises. My objective is to develop a Twitter bot in Node.js that generates a random RGB colour, creates an image of this colour, and tweets it. Thanks to some assistance prov ...

Adding fresh data to an array in mongoose

How can I insert new values into a MongoDB database? Currently, the Grocery Schema contains an array of users in which I want to store all user IDs related to itemName. However, I'm unsure about how to accomplish this. var mongoose = require('mo ...

The conditional ng-class styling will be applied to each and every div on the page

For a patient, I have a modal displaying a list of card numbers. If the card is set as the default card, it should have a grey background, based on a true value for the object. <td ng-repeat="obj in paymentAndShipping"> <div ng-click= ...

What is the best placement for the deviceready event in a multi-page PhoneGap application?

1) When working with multiple pages PhoneGap applications that may call the PhoneGap API, should the deviceready listener be placed on every page or is it enough to include it on the first page only? 2) Utilizing AngularJS routing along with <ng-view&g ...

I'm having trouble establishing a connection between Firebase Realtime Database and Vue.js

I am having trouble establishing a connection to the Firebase Realtime Database. import { initializeApp } from "firebase/app"; // Remember to add any necessary SDKs for Firebase products // For more information, visit: https://firebase.google.com ...

Creating a JSON object in AngularJS is a simple and straightforward process

Is it a good practice to create a JSON object in AngularJS this way? Or is there a better solution to achieve the desired format? Edit question: I am trying to create an object in JSON format as shown below. I have written the code but facing difficulty ...

What is the best way to utilize arrays within a loop to generate various outputs?

I have been working on developing a program that will prompt the user for all necessary information to generate an invoice. The idea is that the program will allow users to add multiple products or services, with each input creating a new entry in an array ...

Add a checkbox element to a web API using ReactJS

I'm currently learning react and encountering an issue with checkboxes that I can't seem to resolve. I am working on a modal for updating and inserting data in a .net core web api, which is functioning correctly. However, within the app, I'm ...

What is the best way to add an element directly following another within the document's head section?

In my HTML project, I am using JavaScript to insert style elements into the head section. I have implemented a function that should inject styles into a specific id within the head tags. This is a snippet of my current HTML code: function insertAtElemen ...

What are the steps to develop a progress bar using PHP and JavaScript?

In the application I'm developing, PHP and JavaScript are being used extensively. One of my tasks involves deleting entries from the database, which is a time-consuming process. To keep the end-user informed, I would like to provide updates on the pr ...

Steps to assign a JSON file to an array within an object in Angular

What is the best way to assign a JSON file to an array within my "Client" object? I currently have a JSON file named Clients.json with the following structure: { "clients": [ { "firstName": "nameA", "lastName": "lastA", "doctorsNam ...

What is the best way to ensure that a server response is received before initiating an Apollo Graph QL Query

Is there a way to call a Graph QL Query after data is received from the useEffect hook? The challenge I am facing is that hooks cannot be called conditionally. If I remove the condition, loadedAnime will become undefined. How can I overcome this limitati ...