Adam Stück Adam Stück -3 years ago 40
Javascript Question

How to make an array out of objects automatically

Hi guys right now I'm making my array like this:

var piece1 = new DialoguePiece(null, questions[0], 0, 0, 4, 1);
var piece2 = new DialoguePiece(null, questions[1], 1, 0, 2, 3);
var piece3 = new DialoguePiece(scripts[1], null, 2, 1, 2, 2);
var piece4 = new DialoguePiece(scripts[2], null, 3, 1, 3, 3);
var piece5 = new DialoguePiece(scripts[0], null, 4, 0, 5, null);
var piece6 = new DialoguePiece(scripts[3], questions[2], 5, 4, 6, null);
var piece7 = new DialoguePiece(scripts[4], null, 6, 5, 7, null);
var piece8 = new DialoguePiece(scripts[5], null, 7, 6, null, null);

var pieces = [piece1,
piece2,
piece3,
piece4,
piece5,
piece6,
piece7,
piece8];


But I am wondering is there an easier way to do this? Like for example:

var pieces = GetObjectsByName(DialoguePiece);


Thanks.

Answer Source
function DialoguePiece(){
  DialoguePiece.all.push(this);
  ...
} 
DialoguePiece.all=[];

You could simply store them in an array, everytime the constructor is called ( being a property of the constructor itself makes it easy to reference ). To access you can do:

for(var i=0;i++<10;)
  new DialoguePiece();

console.log(DialoguePiece.all);
//its a normal array, so you could also do:
console.log(DialoguePiece.all.map(dia=>dia.name||"doesnt exist"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download