const defaultEmployee = {
tasks: []
}
const employees = []
const NUMEBR_OF_EMPLOYEE = 5
const INDEX_CEO = 0
for (let index = 0; index <= NUMEBR_OF_EMPLOYEE; index++) {
const employee = {
...defaultEmployee,
role: index
}
if (employee.role === INDEX_CEO) {
employee.tasks.push({ salary: 10.000 })
} else {
employee.tasks.push({ salary: 1.0 })
}
employees.push(employee)
console.log(defaultEmployee)
}
console.log(employees)
Result:
Top comments (1)
When you use the spread operator
...defaultEmployee
to copy your original object, it only creates a shallow copy of the original object.The
tasks
array on each of your new objects is just a reference to the original array, which means every item you push onto the array will appear on all of your objects.One way you could approach this is to use a class rather than a plain object:
If we're going to go down that road, then we might also think about naming the properties a bit differently, since putting
salary
in atask
property feels a bit odd. We an also use a couple of functions to create new employees with specific properties for CEO or Manager roles while we're at it: