简体   繁体   English

如何将 object 转换为对象数组

[英]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,
      },
    ],
  },
];

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM