Home > other >  How can I create a list of objects dinamically in JavaScript?
How can I create a list of objects dinamically in JavaScript?

Time:06-27

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  
}

CodePudding user response:

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.

  • Related