-4

Basically I have this data:

const arrayWithDates = [{2023-06-02: 2, 2023-06-21: 6},{
{2023-06-29: 2, 2023-06-23: 1}]

But I would like to transform the previous array to this:

Const arrayTransformed = [[{count:'2', date:'2023-06-02'}, {count:'6', date:'2023-06-21'}],[{count:'2', date:'2023-06-29'},{count:'1', date:'023-06-23'}]]
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 2
    Asking someone to write code for you is not not a question. What have you attempted? https://stackoverflow.com/help/how-to-ask – ee-4-me Jul 17 '23 at 17:46
  • Your first array is invalid (an extra curly bracket was included on the first line `{`, and the keys are not strings, numbers, or Symbols). Besides that, this seems awfully similar to [Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`](https://stackoverflow.com/q/47863275/215552) – Heretic Monkey Jul 17 '23 at 17:54

2 Answers2

0

Assuming your dates in arrayWithDates are formatted as strings, this should work:

const arrayTransformed = arrayWithDates.map(obj => {
   return Object.entries(obj).map(([date, count]) => {
   return { date, count: count.toString() };
   });
 });
Lavie
  • 136
  • 7
0

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" }
]
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • I think it would reasonable to say this is almost exact same answer as mine, and your additions could have been added as a comment. – Lavie Jul 17 '23 at 18:05
  • @Lavie Funny thing to comment about when both answers are pretty much the same as answers on the duplicate I pointed to 9 minutes before you answered... – Heretic Monkey Jul 17 '23 at 20:05
  • @HereticMonkey lol fair. – Lavie Jul 18 '23 at 03:49