Reputation: 424
I've a use case in which I need to generate the object with present and previous month's(or quarter or week) data and also the difference between them too.
I've got the whole data. But I'm confused on how to perform the subtraction among object values and create a new object with it's results.
For example, I've the following data.
data = {
"variables": [
"heat",
"humidity"
],
"lables": [
"February",
"January",
"December",
"November",
"October",
"September"
],
"values": [
[
300,
40,
0,
7000,
250,
150
],
[
400,
10,
0,
8000,
150,
50
]
]
}
Now I want to generate the following object.
result= {
"variables": [
"heat",
"humidity"
],
"lables": [
"February",
"January",
"December",
"November",
"October",
"September"
],
"values": [
[
300,
40,
0,
7000,
250,
150
],
[
400,
10,
0,
8000,
150,
50
]
],
"current":{
"_id":"February",
"heat":300,
"humidity":400
},
"previous":{
"_id":"January",
"heat":40,
"humidity":10
},
"difference":{
"heat":260,
"humidity":390
},
}
Here, the lables
and variables
are completely dynamic. i.e, if there is only one variable is available, there will be only one array values
array. Is there any way to achieve the above result?
Upvotes: 0
Views: 41
Reputation: 9812
You can try something like this:
data.current = {
_id: data.lables[0],
...(data.variables.reduce((obj, variableName, variableIndex) => {
obj[variableName] = data.values[variableIndex][0]
return obj
}, {})
}
data.previous = {
_id: data.lables[1],
...(data.variables.reduce((obj, variableName, variableIndex) => {
obj[variableName] = data.values[variableIndex][1]
return obj
}, {}))
}
data.difference = {
...(data.variables.reduce((obj, variableName, variableIndex) => {
obj[variableName] = data.current[variableName] - data.previous[variableName]
return obj
}, {}))
}
Upvotes: 2