Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign a value to a specific object property in Array?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading