0

Is it possible to loop through a data set of objects as associative arrays?

I have a bunch of JSON data, and would like to loop through all of the data sets and pull out a property in each object.

for example:

for ( var i = 0; i <= 20; i++){
var oblivion = i;
var myObject = new MYobject( oblivion);
oblivionLoader(myObject);
}


function oblivionLoader(myObject)
{
 for ( i = 1; i<=2; i++)
 {
   var changer = myObject.oblivion[i];
   var infoText = GetDetailsText(changer);
   infoText.html(myObject.toString());
 }
}

If this is possible please show me how. Otherwise I am concluding it is impossible...

user763349
  • 847
  • 2
  • 11
  • 13
  • Is it your intention to overwrite the preceding myObject in the 1st loop? – Alex K. Jul 15 '11 at 15:19
  • 2
    what is `MYobject` and i don't see an array. – Daniel A. White Jul 15 '11 at 15:19
  • I did this example in a hurry without thinking. Basically I need to grab all of the data, and pass it through one at a time into a function that loops through the data. – user763349 Jul 15 '11 at 15:24
  • Imagine making a timed display of data on a screen based on looping through this object is essentially my goal. 90% of everything is written correctly, but I am having an issue looping through this objects properties. – user763349 Jul 15 '11 at 15:26
  • your example code is very confusing; my best guess is that you're looking for `for..in` loops - see eg http://stackoverflow.com/questions/587881/how-to-iterate-over-every-property-of-an-object-in-javascript-using-prototype/588276#588276 – Christoph Jul 15 '11 at 15:30

1 Answers1

3

you can use a for in loop to loop through properties of an object.

var myObject = { prop1:"1", prop2:"2", prop3:"3" }, 
    property;

for ( property in myObject ) {
    if ( myObject.hasOwnProperty( property ) { 
        alert( myObject[property] );
    }
}

the bracket and dot syntax is interchangeable in JavaScript.

That being said, I have no idea what you're trying to do in you're example...

Greg Guida
  • 7,302
  • 4
  • 30
  • 40
  • 1
    you're missing a `var` declaration for `property` (assuming you don't want it to be global...); also, I recommend checking `hasOwnProperty()` as well... – Christoph Jul 15 '11 at 15:32
  • How would you grab a paticular order in the my object loop? Since the loop goes 21 times. I how do I grab the object from the 13 loop? – user763349 Jul 15 '11 at 20:23
  • I don't think you understand the difference between arrays and objects in JavaScript, take a look at this http://stackoverflow.com/questions/874205/javascript-what-is-the-difference-between-an-array-and-an-object – Greg Guida Jul 15 '11 at 20:30