If you need to add multiple elements of objects to an array with the same values, there are various methods you can use.
Method 1: Use Array.fill
Note: This method will assign the exact same object to each index of the array from 0 to the length of the array. Learn more here.
type Person = { firstName: string; lastName: string; age: number; };
const numberOfPeople: number = 3;
const defaultPerson = { firstName: '', lastName: 'Smith', age: 0 };
// Fill all elements in the array with the same object
const people = Array(numberOfPeople).fill(defaultPerson);
// You can then change one element by assigning a new object
people[1] = { firstName: 'unique', lastName: 'unique', age: 0 };
This approach helps save memory when default values are consistent, and only new objects are needed for unique individuals.
Method 2: Use Spread Operator and Array.map
If you have an array of different objects but with the same initial values, consider using map.
type Person = { firstName: string; lastName: string; age: number; }
const numberOfPeople: number = 3;
const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };
const people: Person[] = [...Array(numberOfPeople)]
.map(_ => ({ ...defaultPerson })); // Creates a shallow copy of the object
Method 3: Use Array.from
type Person = { firstName: string; lastName: string; age: number; }
const numberOfPeople: number = 3;
const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };
const people: Person[] = Array.from(Array(numberOfPeople), _=>({...defaultPerson}));
Method 4: Use for...of
type Person = { firstName: string; lastName: string; age: number; }
const numberOfPeople: number = 3;
const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };
const people: Person[] = [];
for (const _ of Array(numberOfPeople)) people.push({...defaultPerson})