Group JSON data (sent by multiple devices) by date

Asked

Viewed 90 times

0

I’m working on a project with websokets and I’m not sure how to solve the following problem. I receive via WS JSON data from various devices. Each device sends a value once per second. In the client I receive data from various devices so.

{ab1: {date: "2019-06-12 12:45:50", value: "31"}}
{cd2: {date: "2019-06-12 12:45:50", value: "34"}}
{ab1: {date: "2019-06-12 12:45:51", value: "32"}}
{cd2: {date: "2019-06-12 12:45:51", value: "36"}}
...

So far I’ve managed to organize the data by id:

ws.onmessage = function (evt) { 
    var data = JSON.parse(evt.data);
    var id = data.id;
    var date = data.date;
    var value = data.value;
    datas[id] = {'date':date,'value':value};
};

the result is like this:

{ab1:{date:"2019-06-12 12:45:50",value:"31"}, cd2:{date:"2019-06-12 12:45:50",value:"34"}}
{ab1:{date:"2019-06-12 12:45:51",value:"32"}, cd2:{date:"2019-06-12 12:45:51",value:"36"}}
...

But how do I need to group the data by date to later create the average of the received values every second and display in a graph that updates once per second. This format does not facilitate.

Ideally the above data would be in the following format:

{2019-06-12 12:45:50: {id: "ab1", value: "31"}, {id: "cd2", value: "34"}}
{2019-06-12 12:45:51: {id: "ab1", value: "32"}, {id: "cd2", value: "36"}}

I needed an orientation to convert the received data in this format.

1 answer

0

See if this helps you.

Instead of returning each object like this:

{2019-06-12 12:45:50: {id: "ab1", value: "31"}, {id: "cd2", value: "34"}}

Returns like this:

{date: "2019-06-12 12:45:50": [{id: "ab1", value: "31"}, {id: "cd2", value: "34"}]}

Example:

const arr = [

{ab1: {date: "2019-06-12 12:45:50", value: "31"}},
{cd2: {date: "2019-06-12 12:45:50", value: "34"}},
{ab1: {date: "2019-06-12 12:45:51", value: "32"}},
{cd2: {date: "2019-06-12 12:45:51", value: "36"}},

]

const output = [];

arr.forEach(i => {

  const id = Object.keys(i)[0];

  const date = i[id].date, value = i[id].value;

  const obj = output.find(i => i.date === date);

  if(!obj) {

    output.push({date: date, data: [{id: id, value: value}]});

  }

  else {

    obj.data.push({id: id, value: value});

  }

});

document.write(JSON.stringify(output));

console.log(output)

  • interesting, but the problem is that the json messages arrive one at a time in real fear. I should be able to process the data that comes once a second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.