Search code examples
arrayslodashdate-fns

How to fill an array with unique ids and date?


I want to populate an object array with unique ids and an increment of Date.

This is what I want to achieve:

[
  {
    id: '1',
    date: Mon Mar 07 2022, // date object
  },
  {
    id: '2',
    date: Tues Mar 08 2022, // date object
  },
  {
    id: '3',
    date: Wed Mar 09 2022, // date object
  },
  ...
];

I've tried the following:

import uniqueId from 'lodash/uniqueId';
import add from 'date-fns/add';

const startDate = Mon Mar 07 2022 // this is a date object

const time = new Array(7).fill({
      id: uniqueId()
      date: add(startDate, { days: 1 }),
    });

But this gives me the same id and the same date for each object.


Solution

  • Use lodash's _.times() to create an array of, and use the generated index to create the id, and increment the date (sandbox):

    const time = times(7, (index) => ({
      id: index + 1,
      date: add(startDate, { days: index })
    }));
    

    Without lodash you can use Array.from() to create the array (sandbox):

    const time = Array.from({ length: 7 }, (_, index) => ({
      id: index + 1,
      date: add(startDate, { days: index })
    }));
    
    console.log(time);