You can map each record to an an array by converting the object to entries.
You will need to map each record's key to a date
field and the associated value to a count
field.
const arrayWithDates = [
{ '2023-06-02': 2, '2023-06-21': 6 },
{ '2023-06-29': 2, '2023-06-23': 1 }
]
const arrayTransformed = arrayWithDates.map(record =>
Object.entries(record).map(([date, count]) =>
({ count: `${count}`, date })));
console.log(arrayTransformed);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Output
[
[
{ "count": "2", "date": "2023-06-02" },
{ "count": "6", "date": "2023-06-21" }
],
[
{ "count": "2", "date": "2023-06-29" },
{ "count": "1", "date": "2023-06-23" }
]
]
If you want to flatten the data, call flat()
.
const arrayWithDates = [
{ '2023-06-02': 2, '2023-06-21': 6 },
{ '2023-06-29': 2, '2023-06-23': 1 }
]
const arrayTransformed = arrayWithDates.map(record =>
Object.entries(record).map(([date, count]) =>
({ count: `${count}`, date }))).flat();
console.log(arrayTransformed);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Output
[
{ "count": "2", "date": "2023-06-02" },
{ "count": "6", "date": "2023-06-21" }
{ "count": "2", "date": "2023-06-29" },
{ "count": "1", "date": "2023-06-23" }
]