I have an array with objects like this:
[{Date: null, Dossie1: null}, {Date: null, Dossie1: null}, {Date: null, Dossie1: null}]
And i need to assign to each specific objects property a value.
let dataset = Array(dates.length).fill(objectTemplate)
for (let i=0; i<dates.length; i++) {
dataset[i].Date = dates[i]
}
But the problem is that when i did it.
Each object is assign with the last item.
For instance if dates has 3 value [1,2,3].
Property in array dataset will be assign 3 not 1,2,3
>Solution :
You can fill an array with a callback that returns a copy of the template (by using the spread operator).
Array.from({ length: dates.length }, () => ({ ...objectTemplate }))
const
dates = [
{ Date: null, Dossie1: null },
{ Date: null, Dossie2: null },
{ Date: null, Dossie3: null },
],
objectTemplate = { Date: null },
dataset = Array.from({ length: dates.length }, () => ({ ...objectTemplate }));
for (let i = 0; i < dates.length; i++) {
dataset[i].Date = dates[i];
}
console.log(dataset);
.as-console-wrapper { top: 0; max-height: 100% !important; }