I am working on a personal project and I want to display the graph for which i need to prepare the datapoints. The response I have is
{
"size":[
{
"timestamp":"1641329889000",
"size":12345,
"fees":123456,
"cost":168
},
{
"timestamp":"1641387032",
"size":456789,
"fees":4567891,
"cost":249
},
{
"timestamp":"1641435786",
"size":98765,
"fees":987654,
"cost":987
},
]
}
I want the output should be like this
{
"size":{
"timestamp": ["1641329889000","1641387032","1641435786"],
"size": [12345,456789,98765],
"fees": [123456,4567891,987654],
"cost": [168,249,987]
}
}
Can anyone help me out with this
Using .reduce(), you can use a generic function without any hardcoded datapoint names.
const data={size:[{timestamp:"1641329889000",size:12345,fees:123456,cost:168},{timestamp:"1641387032",size:456789,fees:4567891,cost:249},{timestamp:"1641435786",size:98765,fees:987654,cost:987}]};
const result = data.size.reduce((acc, item) => {
const keys = Object.keys(item);
return keys.reduce((keyAcc, key) => ({
...keyAcc,
[key]: acc[key] ? [...acc[key], item[key]] : [item[key]]
}), {});
}, [])
console.log({ size: result});
let obj = {
"size":[
{
"timestamp":"1641329889000",
"size":12345,
"fees":123456,
"cost":168
},
{
"timestamp":"1641387032",
"size":456789,
"fees":4567891,
"cost":249
},
{
"timestamp":"1641435786",
"size":98765,
"fees":987654,
"cost":987
},
]
}
let timestamps = [];
let sizes = [];
let fees = [];
let costs = [];
obj.size.foreach( ( data ) => {
timestamps.push( data.timestamp );
sizes.push( data.size);
fees.push( data.fees );
costs.push( data.cost );
}
let size = { timestamp: timestamps, size : sizes, fees : fees, cost : costs }
let outputObj = { size : size };
console.log( outputObj );
Sure it's simple. :D
{
"size":{
"timestamp": size.map(item => item.timestamp),
"size": size.map(item => item.size),
"fees": size.map(item => item.fees),
"cost": size.map(item => item.cost),
}
}