Map() through array of objects and do math on them

I have this array of objects coming in on a msg.payload.

(the actual array has lots of other key:value pairs that I'm not interested in

[
{
  "id": "99999",
  "signal": "voltage1",
  "timeseries": [
       {
         "time": 1664553600000,
         "value": 2
       },
       {
         "time": 1664553700000,
         "value": 4
       }]
},
{
  "id": "99999",
  "signal": "voltage2",
  "timeseries": [
       {
         "time": 1664553600000,
         "value": 3
       },
       {
         "time": 1664553700000,
         "value": 1
       }]
},
{
  "id": "99999",
  "signal": "current",
  "timeseries": [
       {
         "time": 1664553600000,
         "value": 5
       },
       {
         "time": 1664553700000,
         "value": 4
       }]
}
]

I want to match up the timestamps and do ("voltage1" + "voltage2") * "current"

Then I want to output a new array that has the result for each timestamp.

I started with the map() function, and got here:

const input = msg.payload;

const output = input.map(signal => {
    const container = {};
    container["id"] = signal.id;
    container["signal"] = signal.signal;
    container["timeseries"] = signal.timeseries;
    return container;
});   

msg.payload = output;

return msg;

this does return me new arrays with only the information I'm interested in. But I'm a bit lost on how to do the math operations. I've found math.max() math.sum(), but nothing much more complex.

Anyone have pointers?

Example function node:

// function to find signal and timestamp
const f = (key, t) => i.find(v => v.signal === key).timeseries.find(x => x.time === t).value

const i = msg.payload
const results = [] 

// get array all of timestamps - assuming voltage1 timestamp also exist for voltage2 and current
const timestamps = i.find(v => v.signal === 'voltage1').timeseries.map( k=>k.time ) 

// loop through all timestamps and push result to results array
timestamps.forEach(t => {

        const v1 = f('voltage1', t)
        const v2 = f('voltage2', t)
        const c = f('current', t)
        const result = (v1 + v2) * c 
        // key will be the timestamp
        results.push({ [t]: result })
})

msg.results = results
return msg;

output:

[{
    "1664553600000": 25
}, {
    "1664553700000": 20
}]
1 Like

@bakman2 thank you so much.

This is possibly the most helpful forum on the entire internet thanks to contributors like you. I just learned more about Javascript in 5 minutes than in the last 5 months. Big kudos!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.