-3

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'}]]
2

2 Answers 2

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" }
]
Sign up to request clarification or add additional context in comments.

2 Comments

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 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...
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() };
   });
 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.