4

I have a list of objects all named in this fashion:

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

I know how to loop through p1 and p2 to collect the properties, provided I know how many of these p object literals there are. Here's my problem, I don't always know how many of these p object literals there will be. Sometimes it goes up to p2, sometimes it goes up to p20.

Is there a way to loop through objects if I know they all share the same prefix?

Edit: I can't change how I'm getting the list of objects. It's given to me in that format...

0

4 Answers 4

5

If we make the following assumptions:

  • The objects are global
  • The number suffixes are sequential

...then the following works:

for (var i = 1; window["p" + i] !== undefined; i++) {
    console.log(window["p" + i]); // loop over each object here
}
Sign up to request clarification or add additional context in comments.

2 Comments

so basically test for p# to see if it's undefined, and if it's not, read properties of p#, and if it is undefined, I can stop? let me test this and get back to you. Thank you.
+1 Heh, I just added this solution to my answer, but didn't even see yours until just now!
2

You should have them in an Array referenced by a single variable.

var p = [];
p.push({   
    name:"john",
    hobby:"collects stamps"
}, {
    name:"jane",
    hobby:"collects antiques"
});

Then you'd loop the Array, and enumerate each object...

for( var i = 0; i < p.length; i++ ) {
    for( var n in p[i] ) {
        console.log( p[i][n] );
    }
}

EDIT:

It seems from a comment that these may be arriving as individual variable.

If they're global variables, and if they always have the same p1 naming, 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 a p(n) global returns a falsey value.

So as long as a truthy value is found, and its typeof is 'object', you'll iterate that object.

5 Comments

Ok. I like where this is going. So suppose I have no control over how the data is given to me. How do I push an unknown number of objects into a single array?
@newbieProgrammer: How is the data currently given? Are you saying that the objects are added to the script as individual p1, p2, etc. variables? If so, that makes things a little different.
yes, you're exactly right. The data given to me is as individual p# object literals.
@newbieProgrammer: If they're global variables, then you can access them as properties of the window object. I added a solution to my answer.
...nevermind, I see that this solution has already been given
0

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

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

Push keeps adding stuff into the array in basic sense. You could also pop to remove the last pushed data.

Take a look at the other methods here:

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

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

Comments

0

Why don't you just store them all in one top-level object literal? It will make it easier to enumerate through them.

EG:

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

etc..

[edit]

If they are local vars, are you can't change the format of this data, you might have to use eval. Don't 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 don't suggest using this, I suggest changing the format of the data you are receiving, but this is one possible solution.

5 Comments

I can't control how I'm receiving the list of objects. So to store them all in a single top-level object literal would require some finesse, since I have to read in the input and then reformat before looping through it. If that's the only way, I'll do that.
How exactly are you receiving the list of objects? What scope are you receiving them in?
I'm receiving the list of objects from a response of a post call. So the post response comes to me as plain text, and when I read it, the scope is just what you see.
You should be transferring this data in JSON format rather.. Is that a possibility?
Yes, you're right in that this would be much better in JSON format. Unfortunately, I have no control over how the web service spits out the data to me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.