2

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

0stone0
  • 34,288
  • 4
  • 39
  • 64
Vlad
  • 419
  • 1
  • 10
  • 21
  • 3
    `Array(dates.length).fill(objectTemplate)` this is not an array full of identical objects, this is an array filled with the same object over and over again. – Thomas Feb 02 '22 at 17:21
  • 1
    i see that you looped via for loop 3 times and each time you are calling Date of each Dataset element and storing value in it, hence you are getting output as 1,2,3 please restrict the iteration according to your requirement via conditions(if or filter) – MhnSkta Feb 02 '22 at 17:25
  • 1
    `Array.from(dates, () => Object.assign({}, objectTemplate))` – Andreas Feb 02 '22 at 17:25

1 Answers1

1

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132