Javascript: loop through an unknown number of object literals

I have a list of all objects named this way:

var p1 = {}; var p2 = {}; p1.name = "john"; p1.hobby = "collects stamps"; p2.name = "jane"; p2.hobby = "collects antiques"; 

I know how to go through p1 and p2 to collect properties if I know how many of these p-object literals exist. Here is my problem, I do not always know how many of these p-objects literals will be. Sometimes it rises to p2, sometimes it rises to p20.

Is there a way to iterate over objects if I know that they all have the same prefix?

Edit: I cannot change the way I get the list of objects. It is given to me in this format ...

+4
source share
4 answers

If we make the following assumptions:

  • Objects are global
  • The suffix of a number is sequential

... then the following work is performed:

 for (var i = 1; window["p" + i] !== undefined; i++) { console.log(window["p" + i]); // loop over each object here } 
+5
source

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.

+2
source

Why don't you just save them all in one top-level literal object? This will facilitate listing through them.

EG:

 var MyObj = { p1: {}, p2: {} }; 

etc..

[edit]

If these are local vars, you cannot change the format of this data; you may have to use eval. Do not shoot me:

 var p1 = {}; var p2 = {}; p1.name = "john"; p1.hobby = "collects stamps"; p2.name = "jane"; p2.hobby = "collects antiques"; var found = true, c = 1; while(found) { try { var obj = eval('p' + c); c++; console.log(obj); } catch(e){ found = false; } } 

I do not suggest using this, I suggest changing the format of the data you receive, but this is one of the possible solutions.

0
source

If you have all your data stored in a variable or several variables, you can push it into an array.

 var data = "....JSON"; var a = []; a.push(data); 

Push continues to add material to the array in the main sense. You can also click to delete the last clicked data.

Take a look at other methods here:

http://www.w3schools.com/jsref/jsref_obj_array.asp

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array

0
source

Source: https://habr.com/ru/post/1394429/


All Articles