-1

hello i have a sample data payload with timestamp as below

  {timestamp:"2021-04-09 10:18:48",value:18,id:1},
  {timestamp:"2021-04-09 10:18:49",value:102,id:2},
  {timestamp:"2021-04-09 10:18:53",value:23,id:3},
  {timestamp:"2021-05-10 10:19:07",value:63,id:4},
  {timestamp:"2021-05-10 10:23:16",value:131,id:5},
  {timestamp:"2021-05-10 10:33:59",value:92,id:6},
  {timestamp:"2021-06-11 10:34:16",value:101,id:7},
  {timestamp:"2021-06-11 10:47:50",value:19,id:8},
  {timestamp:"2021-06-11 10:18:43",value:89,id:9},

any ideas how i can "aggregate/transform" the data by "month"/"year" to display a chart displaying e.g. summed value/(year/month) data

tytx t
  • 1
  • 3

1 Answers1

0

You can parse the timestamps and create a Date object.

Then you can generate a string like `MM-YYYY' and group your elements

  let array = [  {timestamp:"2021-04-09 10:18:48",value:18,id:1},
  {timestamp:"2021-04-09 10:18:49",value:102,id:2},
  {timestamp:"2021-04-09 10:18:53",value:23,id:3},
  {timestamp:"2021-05-10 10:19:07",value:63,id:4},
  {timestamp:"2021-05-10 10:23:16",value:131,id:5},
  {timestamp:"2021-05-10 10:33:59",value:92,id:6},
  {timestamp:"2021-06-11 10:34:16",value:101,id:7},
  {timestamp:"2021-06-11 10:47:50",value:19,id:8},
  {timestamp:"2021-06-11 10:18:43",value:89,id:9}
  ]
  
let data = []

array.forEach(obj => {
  let timestamp = obj.timestamp
    console.log('timestamp', timestamp)
  let date = new Date(timestamp)
  let key = date.getMonth() + '-' + date.getFullYear()
  
  let foundObj = data.find(obj2 => obj2.name === key)
    if (foundObj) {
   foundObj.value = foundObj.value + obj.value
  } else {
   data.push( { value: obj.value, name: key })
  }
})  

demo

Apostolos
  • 10,033
  • 5
  • 24
  • 39