Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop an object and get specific value to push an array each

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
like image 608
Bigboss Highlight Avatar asked Dec 22 '25 04:12

Bigboss Highlight


1 Answers

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);
    
like image 78
Fullstack Guy Avatar answered Dec 23 '25 18:12

Fullstack Guy