json object manipulation within a loop is failing to function

I received a JSON object from a web service with the following structure:

var seriesData = [{
    feederId: "PTS113T",
    businessEventCode: "LowVoltage",
    servicePointEventCount: 6,
    startDayID: 20130812,
}, {
    feederId: "PTS113T",
    businessEventCode: "HighVoltage",
    servicePointEventCount: 2,
    startDayID: 20130812,
}, {
    feederId: "PTS113T",
    businessEventCode: "LowVoltage",
    servicePointEventCount: 7,
    startDayID: 20130814,
}, {
    feederId: "PTS113T",
    businessEventCode: "HighVoltage",
    servicePointEventCount: 5,
    startDayID: 20130815,
}];

I need to transform this object into a new format where each startDayID has separate counts for 'LowVoltage' and 'HighVoltage':

var seriesData = [{
    feederId: "PTS113T",
    servicePointEventLowCount: 6,
    servicePointEventHighCount: 2,
    startDayID: 20130812,
}, {
    feederId: "PTS113T",
    servicePointEventLowCount: 7,
    startDayID: 20130814,
}, {
    feederId: "PTS113T",
    servicePointEventHighCount: 5,
    startDayID: 20130815,
}];

To achieve this, I am looping through the original data and organizing it accordingly:

if (seriesData) {
    var modifiedData = [];
    for (var i = 0; i < seriesData.length; i += 2) {
        var data = {};
        
        if ((seriesData[i].startDayID) == (seriesData[i + 1].startDayID)) {
            data.feederId = seriesData[i].feederId;
            data.servicePointEventLowCount = seriesData[i].servicePointEventCount;
            data.servicePointEventHighCount = seriesData[i + 1].servicePointEventCount;
            data.startDayID = seriesData[i].startDayID;
        } else {
            data.feederId = seriesData[i].feederId;
            data.startDayID = seriesData[i].startDayID;

            if (seriesData[i].businessEventCode == 'LowVoltage') {
                data.servicePointEventLowCount = seriesData[i].servicePointEventCount;
                data.servicePointEventHighCount = 0;
            } else {
                data.servicePointEventHighCount = seriesData[i].servicePointEventCount;
                data.servicePointEventLowCount = 0;
            }

       }
        modifiedData.push(data);
    }

Answer №1

give this a shot.

var sampledata = [];

// to verify the existence of startDayID
//and store data related to key(startDayID) temporarily 
var sampleDataKeyMap ={}; 

for (var j = 0; j < collectionData.length; j ++) {
    var obj = collectionData[j];
    var code = obj.startDayID;

    var info = null;

    if(!sampleDataKeyMap[code]){

        // create new if startDayID does not exist
        info = {};

        // saving for later access (in the else statement below)
        sampleDataKeyMap[code] = info; 

        // add it into the array
        sampledata.push(info);

        // set default information
        info.feederId = obj.feederId;
        info.startDayID = obj.startDayID;

    }else{

        // retrieve data from map if startDayID exists
        info= sampleDataKeyMap[code]; 
    }

    if (obj.businessEventCode === 'LowVoltage') {
        info.servicePointEventLowCount = obj.servicePointEventCount;
    } 
    if (obj.businessEventCode === 'HighVoltage') {
        info.servicePointEventHighCount = obj.servicePointEventCount;
    }
}

using "i+=2" can be risky.

Your collectionData may not always have pairs of data for both LowVoltage and HighVoltage.

Therefore, iterate through all the data using i++

Ensure that only the key already exists or not

Answer №2

attempt:

for (let x = 0; x < elementsData.length-1; x += 2) {

Answer №3

Ensure to verify the condition for seriesData[i + 1].startDayID in your loop before proceeding further with the last run.

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

Transform a series of JSON objects into a dataframe and proceed through each step methodically

Currently, I am facing an issue where I have a list with a total of 2549150 elements. Instead of converting the entire list into a dataframe using the pd.json_normalize method at once, I would like to convert it step by step. The plan is to convert the fi ...

Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error. I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handlin ...

Create a soft focus on the background sans any filters

I am in the process of developing a website and have implemented code to blur out the background: CSS #background{ background: url(img/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

The error message "java.lang.ClassCastException: org.json.JSONObject$Null cannot be cast to java.lang.String" indicates that

One specific exception that occurred is a java.lang.ClassCastException, where org.json.JSONObject$Null could not be cast to java.lang.String Printthis>>>>>>userName=user1&passKey=12345678 POST Response Code :: 200 jsonObj>>> ...

Troubleshooting the unresponsive Vue @change event within the <b-form-datepicker/> component

I am in the process of developing a website with both a select form and a datepicker form that will send an API request for data. I aim to have the data update dynamically whenever there is a change in either of these forms, thereby eliminating the need fo ...

What sets apart the methods of populating arrays in iOS?

Greetings Everyone, Let me share a situation with you. I have been trying to populate my array using two different methods. The first method works perfectly fine, while the second one seems to be giving me some trouble. My goal is to change the color ...

The background color changes only on a specific page by selecting a color from the color picker

I created a webpage with a color picker that changes the color of the action bar. However, the action bar color only changes once and I want it to change on all other pages as well. Below is the code I used: <h4>Color Picker</h4> <scrip ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

issues with functions failing to execute properly when clicked

I'm experiencing an issue with a button where I need to call two functions, but it seems like they are canceling each other out. When I check the console, I can see that the functions are linked to specific lines of code. For example, line 1 correspo ...

Utilized controller's isolated scope inheritance to enhance the reusability of the directive

How can I create an isolated scope in a controller to make a reusable directive? Take a look at my code snippet below: (function (app) { // Declare the Template var template = function (element, attrs) { var htmltext = '& ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Utilizing AngularJS with multiple dynamically generated forms on a webpage: Extracting data from each form

I am facing a challenge with a web page I have created that uses PHP to generate forms for updating information via a REST API on a remote server. The structure of the forms is as follows: Textfield: name textfield: description select: type (ng-model="se ...

Java displays Russian characters as "???"

I'm facing an issue with my controller where I need to return a JSON string containing a Russian name, but all I'm getting in response are question marks (invalid characters). @Controller public class ManifestController { @ResponseBody ...

What could be causing the issue with running npx create-react-app my-first-app?

Encountered issues when attempting to execute npx create-react-app. Need assistance troubleshooting the error messages preventing the command from running. View Screenshot of Terminal with stacktrace Error: EPERM: operation not permitted, mkdir 'C:& ...

Unusual array behavior when encountering different values inside and outside of a for loop

Having a function called input(), it compares a string (always 2 characters long) with preset strings and returns the corresponding integer: int input(char *ch){ if(strcmp(ch, "AZ") == 0){ return 1; } else if(strcmp(ch, "BY") == 0){ ...

Choose a specific range of dates using only one Bootstrap Datepicker

Currently utilizing Bootstrap DatePicker version 1.8.0 from this repository. I am looking to select a range within a single Bootstrap DatePicker and require the input values to be sorted in ascending order (as shown in the example below). https://i.sstat ...

Guide to extracting and utilizing a JSON object received from the parent page

Hello, I've been searching online for quite some time and can't seem to find a solution to my question. If anyone could help, I would greatly appreciate it. Below is the code I am working with: <ion-content> ...