Navigating an object array: A step-by-step guide

Here is an example of an object array:

[{
    "AVG_VALUE": "38",
    "MAX_VALUE": "38",
    "SUM_VALUE": "38",
    "MIN_VALUE": "38",
    "METRICID": "100367597885",
    "START": "1449216120000",
    "STARTTIME": "09:02"
}, {
    "AVG_VALUE": "0",
    "MAX_VALUE": "0",
    "SUM_VALUE": "0",
    "MIN_VALUE": "0",
    "METRICID": "100367597885",
    "START": "1449481620000",
    "STARTTIME": "10:47"
}, {
    "AVG_VALUE": "0",
    "MAX_VALUE": "0",
    "SUM_VALUE": "0",
    "MIN_VALUE": "0",
    "METRICID": "100367597879",
    "START": "1449506820000",
    "STARTTIME": "17:47"
}, {
    "AVG_VALUE": "0",
    "MAX_VALUE": "0",
    "SUM_VALUE": "0",
    "MIN_VALUE": "0",
    "METRICID": "100367597886",
    "START": "1449506820000",
    "STARTTIME": "17:47"
}, {
    "AVG_VALUE": "1553",
    "MAX_VALUE": "1553",
    "SUM_VALUE": "1553",
    "MIN_VALUE": "1553",
    "METRICID": "100367597885",
    "START": "1449578820000",
    "STARTTIME": "13:47"
}, {
    "AVG_VALUE": "1543",
    "MAX_VALUE": "1543",
    "SUM_VALUE": "1543",
    "MIN_VALUE": "1543",
    "METRICID": "100367597879",
    "START": "1449579120000",
    "STARTTIME": "13:52"
}, {
    "AVG_VALUE": "1553",
    "MAX_VALUE": "1553",
    "SUM_VALUE": "1553",
    "MIN_VALUE": "1553",
    "METRICID": "100367597886",
    "START": "1449579120000",
    "STARTTIME": "13:52"
}, {
    "AVG_VALUE": "514.3333",
    "MAX_VALUE": "1543",
    "SUM_VALUE": "1543",
    "MIN_VALUE": "0",
    "METRICID": "100367597879",
    "START": "1449652080000",
    "STARTTIME": "10:08"
}, {
    "AVG_VALUE": "10",
    "MAX_VALUE": "10",
    "SUM_VALUE": "30",
    "MIN_VALUE": "10",
    "METRICID": "100367597886",
    "START": "1449652080000",
    "STARTTIME": "10:08"
}, {
    "AVG_VALUE": "30",
    "MAX_VALUE": "30",
    "SUM_VALUE": "30",
    "MIN_VALUE": "30",
    "METRICID": "100367597879",
    "START": "1449705900000",
    "STARTTIME": "01:05"
}, {
    "AVG_VALUE": "30",
    "MAX_VALUE": "30",
    "SUM_VALUE": "30",
    "MIN_VALUE": "30",
    "METRICID": "100367597886",
    "START": "1449705900000",
    "STARTTIME": "01:05"
}]

I am looking to extract the "AVG_VALUE" from this array and create a specific formatted string:

"Date, ANZAHL_FAKTUREN_GESAMT, ANZAHL_VERARB_DATEIEN, VERSENDETE_SPOOL
\n2015/12/04, 0, 38, 0
\n2015/12/07, 0, 0, 0
\n2015/12/08, 1543, 1553, 1553
\n2015/12/09, 514.3333, 0, 10
\n2015/12/10, 30, 0, 30"

To achieve this, I will iterate through my array using the following code:

var j = 0;
    for (var i = 0; i < (data.length + j); i++) {
        if (i % metricNames.length === 0) {
            var date = new Date(null);
            date.setMilliseconds(data[i]['START']);
            body += "\n" + date.customFormat("#YYYY#/#MM#/#DD#");

        }

        console.log("i-j " + (i - j));
        console.log("modulo " + i % metricNames.length);
        console.log("m1 " + metricNames[i % metricNames.length]['METRICID']);
        console.log("m2 " + data[i - j]['METRICID']);

        if (metricNames[i % metricNames.length]['METRICID'] === data[i - j]['METRICID']) {
            console.log(i % metricNames.length);
            body += ", " + data[i - j]['AVG_VALUE'];
        } else { // if there is no value for the metricid no value will be added
            body += ", 0";
            j++;
        }
    }

While this code works with other datasets, in this particular case, the order of the metric values are not consistent causing incorrect results as shown below:

Date, ANZAHL_FAKTUREN_GESAMT, ANZAHL_VERARB_DATEIEN, VERSENDETE_SPOOL
2015/12/04, 0, 38, 0
2015/12/07, 0, 0, 0
2015/12/07, 0, 0, 0
2015/12/08, 0, 1553, 0
2015/12/08, 1543, 0, 1553
2015/12/09, 514.3333, 0, 10
2015/12/10, 30, 0, 30

Any suggestions on how to improve the iteration process to get the correct string output?

//*** This code is copyright 2002-2003 by Gavin Kistner, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="260766564e5449415c08484352">[email protected]</a>
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
  var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
  YY = ((YYYY=this.getFullYear())+"").slice(-2);
  MM = (M=this.getMonth()+1)<10?('0'+M):M;
  MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
  DD = (D=this.getDate())<10?('0'+D):D;
  DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
  th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
  formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
  h=(hhh=this.getHours());
  if (h==0) h=24;
  if (h>12) h-=12;
  hh = h<10?('0'+h):h;
  hhhh = h<10?('0'+hhh):hhh;
  AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
  mm=(m=this.getMinutes())<10?('0'+m):m;
  ss=(s=this.getSeconds())<10?('0'+s):s;
  return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};

var metricNames = null;

for (var i = 0; i < metricNames.length; i++) {
    header += ", " + metricNames[i]['METRICNAME'];
}

Answer №1

Is the issue you're facing related to the order of object attributes?

Sometimes it may look like this:

{
    "AVG_VALUE": "0", 
    "MAX_VALUE": "0",
    "SUM_VALUE": "0",
    "MIN_VALUE": "0",
    "METRICID": "100367597885",
    "START": "1449481620000",
    "STARTTIME": "10:47"
}

And then later it might be in a different order, like this:

{
    "START": "1449481620000",
    "AVG_VALUE": "0", 
    "MIN_VALUE": "0",
    "METRICID": "100367597885",
    "MAX_VALUE": "0",
    "STARTTIME": "10:47",
    "SUM_VALUE": "0"
}

If this is indeed your problem, you can try the following solution:

for (var i = 0; i < data.length; i++) {
    var line = new Array();
    for (var key in data[i]) {
        var pos;
        switch(key) {
            case "STARTTIME": pos = 2; break;
            case "SUM_VALUE": pos = 5; break;
            ...
        }
        line[pos] = data[i][key];
    }
    line = line.join(',');
}

If you need further explanation, feel free to ask in a comment. And if I misunderstood your issue, my apologies :)

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

Revamp the order of Sequelize output

Currently, I am running a complex findAll operation in Sequelize that involves multiple includes. Here is an example of what my code looks like: const versions = yield Version.findAndCountAll({ order: [['createdAt', 'DESC']], attri ...

I am facing an issue where childnodes return as undefined after a clone operation, making it impossible for me to assign their attributes as needed,

There seems to be an issue with changing the attributes of my child nodes as they are returning as undefined. It's possible that the problem arises when the nodes are placed in a list. Upon testing, it was discovered that placing the nodes in a list c ...

A guide on formatting JSON arrays in key-value notation

Trying to retrieve a JSON array from PHP output, which pulls multiple values from the database and converts them to a JSON array. The PHP code in question is: php $result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC"); // defined a seco ...

Preventing automatic interpretation of double curly braces within a Script tag in Handlebars

In my development project, I am constructing a visual representation of a database table along with various web application functionalities. The technologies being utilized include node.js, express, mysql, bootstrap, and handlebars. Within my pages.js fil ...

Issues with Java Array Indexing

I am encountering an issue with Arrays that is causing an error in the debug console: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at com.company.SortTextFile.main(SortTextFile.java:28) I hav ...

Exploring JSON array for values with stdClass nested subarrays

This JSON snippet is a segment of order data from the WooCommerce APIv2 get_order() function. Within the [meta], there are details about product variations chosen by the customer. [meta] => Array ( [0] => stdClass Object ( [key] => pa_size [l ...

Utilizing Javascript executor for selecting radio buttons

Having trouble selecting the 'Yes' and 'No' options on a page, I attempted to use JSExecutor since the normal 'Click()' function was not working. The issue is that while it is able to select the options, the value is not being ...

Receiving input from the "Enter" key is functional in Internet Explorer but not Firefox when utilized in Cognos

Working with Cognos, I'm currently tackling the challenge of capturing the enter key to validate user input before submitting the prompt. If you're not familiar with Cognos, that's okay - any insights on my code are welcome :) This tool is ...

What is the best way to cancel a Promise if it hasn't been resolved yet

Let's consider a situation where I have implemented a search function to make an HTTP call. Each call made can have varying durations, and it is crucial for the system to cancel any previous HTTP requests and only await results from the latest call. ...

Unable to retrieve data from the $.getJSON method

Using $.getJSON in jQuery, I am retrieving the necessary data from the server. Below is an example of how it is structured: $.getJSON("/dataParser/parseVoltage",function(jsondata, status) { if (status == "error") { console.log("Error occurred whil ...

Using JavaScript parameters in a HTML document

I am trying to replicate a page similar to this. The issue I am facing is the inability to use external JS files in ASP.net (as far as I know). Therefore, I am defining the functions and attempting to utilize them within the HTML page instead. <%@ P ...

Issue encountered when attempting to transfer data to MongoDB using custom API

Currently, I have been working on a flutter application that is designed to send data to my custom API built in node js. This API then forwards the data to a MongoDB cluster. While testing the API, everything was functioning correctly and the data was succ ...

Create automatic transcripts for videos, including subtitles and captions

Are there any tools or plugins available that can automatically create a transcript of a video for website playback? For example, generating captions and subtitles in the English language. ...

Sending an Array of Structs to Pthread_Create in C

I'm currently facing a challenge with handling an array that contains 2 structs. My goal is to pass this array into a thread function and be able to manipulate both structs within it. The issue I encountered is that most examples I came across demonst ...

Show and conceal columns in HTML with the help of JavaScript

I need help with a webpage where I want to display a table with 2 columns and two rows (header and body). My goal is to use JavaScript to control the visibility of these 2 columns. The decision to show or hide the columns should be based on the values ...

How can I keep dragging objects on Raphael JS Freetransform without showing the handles?

Hey there! Currently, I am immersed in a new project that hinges on the utilization of Raphael JS alongside the Raphael.Freetransform plugin. The plugin has been performing admirably with smooth transitions so far. Nonetheless, upon utilizing the hideHandl ...

The value appears correctly when displayed in the Console, but it becomes undefined when attempting to store it in a

Working with data fetched from an API, I encountered an issue when trying to access a specific value as a variable in ReactJS. While console logging the value worked perfectly fine, I ran into an error when attempting to use it elsewhere: Cannot Read pr ...

Navigating Information in the Response - Node.js

Currently, I am working on a node.js project that has grown significantly with numerous endpoints. As the project continues to expand, modifying the data within the responses for each endpoint has become quite cumbersome. I find myself constantly navigatin ...

What does the error "Cannot access property 'length' of null when using 'angular'" mean?

I am currently working on counting the initial li items and encountering an issue with 'Cannot read property 'length' of null' after fetching data from the server using a unit test case. Here is my code: import { ComponentFixture, Tes ...

JavaScript function for Removing, Saving, and Updating Quantities in the Shopping Cart

Just starting to learn how to code. I'm working on a basic Book Shopping Cart page: Shopping cart The main objective is to be able to ADD items to the cart, SAVE the cart contents, and REMOVE items from the cart whenever necessary using the template ...