You must have them in the array referenced by one variable.
var p = []; p.push({ name:"john", hobby:"collects stamps" }, { name:"jane", hobby:"collects antiques" });
Then you loop the array and list each object ...
for( var i = 0; i < p.length; i++ ) { for( var n in p[i] ) { console.log( p[i][n] ); } }
EDIT:
As can be seen from the commentary, they can appear as an individual variable.
If these are global variables, and if they always have the same name p1 , then you can access them as properties of the global window object.
var obj; for( var i = 1; obj = window['p' + i]; i++ ) { if( typeof obj === 'object' ) { for( var n in obj ) { console.log( obj[n] ); } } }
This loop will run until p(n) global returns false.
So, while the true value is found, and its typeof is 'object' , you will iterate over this object.
user1106925
source share