Vivek Jhooria
Vivek Jhooria

Reputation: 27

how to convert an object to array of objects

I have data in the following format

const data = 
{
   "sent_total":429,
   "sent_distribution":[
      {
         "date_triggered__date":"2022-12-07",
         "count":92
      },
      {
         "date_triggered__date":"2022-12-08",
         "count":337
      }
   ],
   "delivered":428,
   "delivered_distribution":[
      {
         "timestamp__date":"2022-12-07",
         "count":91
      },
      {
         "timestamp__date":"2022-12-08",
         "count":337
      }
   ],
}

Need help in converting this in the following format which separates the data by the key (which is sent or delivered) to an array of objects.

const data = [
  {
    key: sent,
    value: 429,
    distribution: [
      {
        date_triggered__date: "2022-12-07",
        count: 92,
      },
      {
        date_triggered__date: "2022-12-08",
        count: 337,
      },
    ],
  },
];

Upvotes: 0

Views: 67

Answers (1)

Amirhossein
Amirhossein

Reputation: 2037

Hope it helps:

const data = 
{
   "sent_total":429,
   "sent_distribution":[
      {
         "date_triggered__date":"2022-12-07",
         "count":92
      },
      {
         "date_triggered__date":"2022-12-08",
         "count":337
      }
   ],
   "delivered":428,
   "delivered_distribution":[
      {
         "timestamp__date":"2022-12-07",
         "count":91
      },
      {
         "timestamp__date":"2022-12-08",
         "count":337
      }
   ],
}

const result = [];
Object.keys(data).map((key) => {
  const newKey = key.split("_")[0];
  let index = result.findIndex((resultItem) => resultItem.key === newKey);
  const value = key.includes("_distribution") ? null : data[key];
  const distribution = key.includes("_distribution") ? data[key] : null;
  if(index === -1) {
    result.push({
      key: newKey,
      value: value,
      distribution: distribution
    });
  } else {
    if(value)
      result[index].value = value;
    if(distribution)
      result[index].distribution = distribution;
  }
});
console.log(result);

Upvotes: 1

Related Questions