skip to Main Content

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

Answers


  1. 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() };
       });
     });
    
    Login or Signup to reply.
  2. 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" }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search