Understanding and aggregating data from JSON files

I am in possession of a group of json values outlined below

{"labels":[ "time", "softirq", "user", "system", "nice", "iowait" ], "data":[ [ 1490088352, 0, 14.64646, 3.53535, 0, 1.0101 ], [ 1490088351, 0, 27.77778, 3.0303, 0, 0 ], [ 1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761 ] }

My aim is to analyze this json file. I intend to add up the values for

{ "softirq", "user", "system", "nice", "iowait"}
labels and store them in a separate variable named "sum". The anticipated output should resemble the following:

{ "time" : 1490088352 , "sum": "the calculated total value "}
{"time" : 1490088351 , "sum": "the calculated total value "}
{"time" : 1490088350 , "sum": "the calculated total value "}

If anyone could provide assistance with this query, it would be greatly appreciated.

Answer №1

Utilize the Array#reduce method to condense an array into a single value

Array.slice(1) can be used to retrieve an array without the first element

var data = {
  "labels": ["time", "softirq", "user", "system", "nice", "iowait"],
  "data": [
    [1490088352, 0, 14.64646, 3.53535, 0, 1.0101],
    [1490088351, 0, 27.77778, 3.0303, 0, 0],
    [1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761]
  ]
};
var op = [];
data.data.forEach(function(el) {
  var obj = {
    time: el[0]
  };
  obj.sum = el.slice(1).reduce(function(a, b) {
    return a + b;
  });
  op.push(obj);
});
console.log(op);

Answer №2

Let's start by loading the data:

var info = {
  "keys": ["timestamp", "task1", "task2", "task3", "task4", "task5"],
  "dataValues": [
    [1490088352, 0, 14.64646, 3.53535, 0, 1.0101],
    [1490088351, 0, 27.77778, 3.0303, 0, 0],
    [1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761]
  ]
};

Next step is to compute the sum of tasks:

var updatedInfo = info.dataValues.map(function(task){return {"timestamp":task[0], "total": task.splice(1, task.length).reduce((a, b) => a + b, 0)};});

Answer №3

    var info = {
  "categories": ["timestamp", "softirq", "user", "system", "nice", "iowait"],
  "values": [
    [1490088352, 0, 14.64646, 3.53535, 0, 1.0101],
    [1490088351, 0, 27.77778, 3.0303, 0, 0],
    [1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761]
  ]
};

var dataValues = info.values;

var processedData = [];
var individualData={};

for(var k in dataValues){
  total=0;
  individualData={};
  for(var m=1,n=dataValues[k].length;m<n;m++ ){
    total+=dataValues[k][m];
  }

  individualData.timestamp=dataValues[k][0];
  individualData.total=total;
  processedData.push(individualData);

  console.log(processedData);
}

Answer №4


var array = {"labels":[ "time", "softirq", "user", "system", "nice", "iowait" ], "data":[ [ 1490088352, 0, 14.64646, 3.53535, 0, 1.0101 ], [ 1490088351, 0, 27.77778, 3.0303, 0, 0 ], [ 1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761 ]] };
var output = [];
for(var i = 0; i < array.data.length; i++){
    var object = {};
    object.time = array.data[i][0];
    object.sum = 0;
    for(var j = 1; j < array.data[i].length; j++){
        object.sum += array.data[i][j];
    }
    output.push(object);
}
console.log(output);

Answer №5

If you want to calculate sums based on specific labels and group them by time, one approach could be to utilize an array for the labels you are interested in and a hash table for grouping by time.

var data = { "labels": ["time", "softirq", "user", "system", "nice", "iowait"], "data": [[1490088352, 0, 14.64646, 3.53535, 0, 1.0101], [1490088351, 0, 27.77778, 3.0303, 0, 0], [1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761]] },
    labels = ["softirq", "user", "system", "nice", "iowait"],
    result = data.data.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a[0]]) {
                hash[a[0]] = { time: a[0], sum: 0 };
                r.push(hash[a[0]]);
            }
            hash[a[0]].sum += labels.reduce(function (r, l) { return r + (a[data.labels.indexOf(l)] || 0); }, 0);
            return r;
        };
    }(Object.create(null)),[]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №6

    var data = {
      "labels": ["time", "softirq", "user", "system", "nice", "iowait"],
      "data": [
        [1490088352, 0, 14.64646, 3.53535, 0, 1.0101],
        [1490088351, 0, 27.77778, 3.0303, 0, 0],
        [1490088350, 0.49751, 12.93532, 2.98508, 0, 4.47761]
      ]
    };
    var processedData = [];
for(var x = 0; x < data.data.length; x++){
  var jsonData = {"time" : data.data[x][0], "sum" : 0}
  for(var y = 1; y < data.data[x].length; y++){
        jsonData.sum += data.data[x][y];
  }
   processedData.push(jsonData)
}
console.log(processedData)
    

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

Convert a string with the characters '"' retrieved from a MySQL database into JSON

After creating a JSON object and storing it in MySQL, I encountered an issue when trying to retrieve and parse it. When I stringify the JSON object, the properties are being enclosed in double quotes causing issues when parsing the retrieved string. Below ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

Display contents from a JSON file

I need to extract unique locality values from a JSON file in Python, but my current code is only printing the first few entries and not iterating through all 538 elements. Here's what I have: import pandas as pd import json with open('data.json ...

I am experiencing an issue in Next.js where the styling of the Tailwind class obtained from the API is not being applied to my

Having an issue with applying a bg tailwind class to style an element using an API. The class text is added to the classlists of my element but the style doesn't apply. Below are the relevant code snippets: //_app.js component import "../index.css"; i ...

Having trouble displaying images from the images folder in React

Currently working on a memory card game using React, but struggling to access the photos in the img folder from app.js. In my app.js file, I attempted to include the photos like so: Even though I have specified a URL for the pictures, they are not appear ...

Express 4 Alert: Headers cannot be modified once they have been sent

I recently upgraded to version 4 of Express while setting up a basic chat system. However, I encountered an error message that says: info - socket.io started Express server listening on port 3000 GET / 304 790.443 ms - - Error: Can't set headers ...

Using Javascript to efficiently remove elements with AJAX

Currently, I am learning the basics of HTML and focusing on tasks such as login/logout functionality, creating users, and deleting users (only permitted when logged in as an admin). For updating a user password, I have utilized PUT, for creating a user ac ...

One can pass parameters to a promise's success callback within AngularJS using $q

I have encountered a situation that is similar to the one described in this post, but I am still unsure about how to implement it. I could use some assistance with setting up a successful callback. This is the current functioning code: function getStuff( ...

ShadowBox not displaying Vimeo videos

I can't figure out why my Vimeo videos are not appearing in a Shadowbox. I have followed the steps I know to be the simplest, which involve copying the example directly from the github page and then updating the shadowbox paths to match the locations ...

An issue with displaying images has been identified within Next.js, resulting in an error message related to the hostname

Encountering an error when using next js Image next.config.js: module.exports = { images: { domains: ['localhost'], }, }; Error image: https://i.stack.imgur.com/RvsdH.png I am struggling to understand how to correctly set up the image ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

Setting multiple cookies with the setHeader method in NodeJs is a powerful capability that allows developers

Currently working on a project using node js, and I've encountered an issue with setting two different cookies. Every time I try to set them, the second cookie ends up overwriting the first one. Check out the code snippet below that I'm currently ...

"Incorporating JSON and Ajax to dynamically populate one select based on the selection in another select

I need to display data from a JSON file in select options, and here is the structure of my JSON file: [{ "vehicle": "car1", "type": [ {"name" : "BMW", "details" : [{ "color" : "red", "price" : "50000" }, ...

Creating a simple bootstrap code for developing plugins in Wordpress

After successfully coding in Brackets with the Theseus plugin on my local machine, I encountered a problem when attempting to transfer my code to a Wordpress installation. The transition from Brackets to Wordpress seems far more complicated than expected. ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

Personal Information Management

After making a request for stormpath user custom data, I used the following code: res.render('home', { title: 'home', user: req.user.customData, }); Instead of receiving a JSON object of custom data as expected, a URL ('') ...

Only execute the NPM script if there is a staged JavaScript file

How can I ensure that an NPM script runs only when a JS file is staged, specifically after a pre-commit git hook (using Husky)? The scripts in my package.json are as follows: "scripts": { ... "test": "jest", "precommit": "npm test", ... }, ...

Partial implementation of jQuery datepicker feature facing technical issues

Greetings, I have a functional datepicker implemented in my code as follows: <link rel="stylesheet" href="uidatepicker/themes/blitzer/jquery.ui.all.css"> <script src="uidatepicker/jquery-1.5.1.js"></script> <script src="uidate ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...