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 can I create a list of objects dinamically in JavaScript?

I’m trying to create an object then put it into an array. But (I guess) when I create a new object the objects inside of the array is getting modified as well, so all the array is getting the same object.
Is something like the code below. How can I make an array of differents objects?

var randomCode = []
var fligthRange = []
var maintenanceArr = []
var results = {ID: '', range: '', maintenance: ''} //the object
var finalResults = [] //the array of objects
var counter = 0

function send(){     //this function is called when a button is clicked on html
  results.ID = randomCode[counter]
  results.range = fligthRange[counter]
  results.maintenance = maintenanceArr[counter]
  finalResults[counter] = results
  counter++
}

>Solution :

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

Just build the object literal in the function itself:

function send(){
  finalResults[counter] = {
    ID: randomCode[counter], 
    range: fligthRange[counter], 
    maintenance: maintenanceArr[counter]
  }
  counter++
}

You will get a new instance added to the array every time the function is called.

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