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

How can I effectively display a blank menu item for the SelectField component in Material-UI within a React application?

I am using the select-field component from the material-ui framework version 0.15.4 with React version 15.4.0. I am attempting to add a blank menu-item to the select-field in order to allow for deselecting a value in the dropdown field when clicked. Howeve ...

How to handle a JSON field that could either be a JSONObject or JSONArray in Java

Currently, I am using the json.org library to handle my JSON data. However, I've encountered a challenge with a field named "messages" that can be presented as either null, a JSONObject (for one message), or a JSONArray (for multiple messages). Dealin ...

What's the best way to adjust the width of the <Input> component in Reactstrap?

How can I adjust the width of an input element in Reactstrap to be smaller? I've attempted to set the bsSize to small without success <InputGroup> <Input type="text" name="searchTxt" value={props.searchText ...

Tips for composing a hyperlink within a property

I'm a newbie to Vue.js and facing a challenge with assigning a property to a link. I'm unsure of how to write the "counter" variable from "data" in order for it to properly function as intended. export default { name: 'app', data ( ...

Issues encountered with Angular POST requests

I have established a registration and login system using passport.js. Additionally, I am incorporating Angular.js in the front-end. However, when Angular is used, the user signup process does not work as expected. Below you can find the code snippets for b ...

Angular: Issue with Controller Constructor Function Executing Repeatedly

My concern lies in the fact that the Controller constructor seems to be executing multiple times. It appears that if I have 2 Directives associated with a specific Controller, it runs 2 + 1 times, and for 3 Directives, it runs 3 + 1 times...and so on. This ...

An angular component that is functioning properly when connected to a live server, however, it is experiencing issues when trying to run `

I tried integrating versitka into my Angular component by placing the version HTML file and all necessary assets in the appropriate directories. However, when I run ng serve, only the HTML file seems to be working, while the CSS and images fail to load. I ...

The JSON request sent to Alexa does not align with the specified Intent Schema

I am currently running an application server using Express with the following versions: "body-parser": 1.14.2", "express": "^4.13.3", "parse-http-header": "^1.0.0", "x509": "^0.2.3") Node v5.4.1 NPM v3.3.12 After successfully testing the SSL connection b ...

Guide on utilizing the carousel component in Bootstrap and populating it with data generated from Node.js

My goal is to design a carousel that displays 5 different pieces of information pulled from a separate app.js file. I attempted to implement a forEach loop, but encountered issues when trying to create a second Bootstrap carousel container. Here's th ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

Selecting a date in Jade's date picker

I'm currently facing an issue with getting a datepicker to function properly using Jade in a node.js and express framework. Within index.jade, I am loading the necessary javascript files like this: link(type='text/css', href='css/ui-l ...

What is the best method to detect a change in scroll position on a webpage using JavaScript?

Is there a way to trigger an event when the page's scroll position changes? I'm interested in creating a dynamic table of contents similar to (where the active item changes as you scroll). Can this be achieved without directly accessing the cu ...

Having trouble with a basic API Get request?

I'm trying my hand at making a simple get request to fetch a random quote from an API. When I hardcode the change of the quote on button click, everything works smoothly. $(document).ready(function() { $("#quotebtn").on('click', functio ...

Updating state from a React mapping component: A step-by-step guide

I am working on an API that needs data filtering and then I want to place the filtered data into a state export default class ModifyPage_Single extends React.Component { constructor(props) { super(props) this.state = {data:[],idd:" ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

Is it possible to utilize JSX independently of React for embedding HTML within a script?

Is it possible to incorporate inline HTML within a script using a library such as jsx? <script src="jsx-transform.js"></script> <script type="text/jsx"> define('component', function () { return (<div>test html code< ...

Utilize lodash to trim the object key

I am looking for a solution to remove occurrences of the object key y_ and achieve an output similar to useroutput: var user =[{"data":"2","y_data1":1},{"data":"4","y_data1":3,"y_data2":3}] var useroutput=[{"data":"2","data1":1},{"data":"4","data1":3, ...

The process of parsing JSON to send a verification code from the server to email is experiencing technical difficulties

Consider the following code snippet : @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.register); emailto= (EditText)findViewById(R.id.editText3 ...

The HTML portion of the AWS SES template contains multiple lines

My current challenge involves using AWS SES to send emails. I have been referring to the documentation provided at https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html. However, the sample template's HTML section is t ...