I've got some case to loop an object which has multiple keys and get specific value and push to an array each, I hope anyone in this forum can help me thanks
[{
"total_sms": 887,
"total_submitted": 101,
"total_in_queue": 696,
"total_processed": 0,
"total_delivered": 0,
"total_failed": 0,
"date": "2019-08-06"
}, {
"total_sms": 888,
"total_submitted": 102,
"total_in_queue": 697,
"total_processed": 0,
"total_delivered": 0,
"total_failed": 0,
"date": "2019-08-06"
}]
expected
total_sms = [887,888]
total_submitted = [101,102]
and etc
You can use Array.reduce to group by the keys of each object in your array. The keys of each object can be obtained from Object.keys.
Now for each key in the object if it is present then just add it to the array else create a new array and add that element:
const data = [{
"total_sms": 887,
"total_submitted": 101,
"total_in_queue": 696,
"total_processed": 0,
"total_delivered": 0,
"total_failed": 0,
"date": "2019-08-06"
}, {
"total_sms": 888,
"total_submitted": 102,
"total_in_queue": 697,
"total_processed": 0,
"total_delivered": 0,
"total_failed": 0,
"date": "2019-08-06"
}];
const grouped = data.reduce((acc, ele) => {
const keys = Object.keys(ele);
keys.forEach(key => acc[key] = acc[key] ? acc[key].concat(ele[key]) : [ele[key]]);
return acc;
}, {});
console.log(grouped);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With