Stranded Kid
Stranded Kid

Reputation: 1395

How to iterate over an Array of objects with Ext.iterate (or JS)?

I know there is plenty of answers for this question on the net, but still I can't make it work.

After a callback on a JSON POST, I'm retrieving an Array of Object. On the console log of the browser, the array is like this :

 [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

where inside each object, there is stuff like :

 id4blob: "1084"

so I assume the array could be like this (correct me if I'm wrong):

 [{id4blob: "1084"},{id4blob: "2008"}, [...]]

The array is stored in a variable called stationsParse

I want to iterate over these values, I've found

  Ext.iterate

So I did this :

Ext.iterate(stationsParse, function(key, value) {
   console.log(key + value);
});

and then tried this (which seems yo be the same but in pure JS)

for (key in stationsParse) {
  var value = stationsParse[key];
  console.log(key + value);
}

But none is working, nothing is displayed in my console. Still, the function is well triggered, I can see it into Chrome console, but the for is ignored.

What Am I doing wrong ? Is this the correct way to iterate over an array of objects ?

Upvotes: 0

Views: 14832

Answers (3)

Einar
Einar

Reputation: 243

I was able to make this work:

for (var i in family) {
    console.log( family[i]["name"] );
}

in this tutorial on Codecademy, where family is an array of objects.

The only difference I can see is the var in front of my iterator variable i.

Upvotes: 0

user1578653
user1578653

Reputation: 5038

Try something like this:

var stationsParse = [{id: 1, someproperty: 2}, {id: 2, someproperty: 101}];

Ext.each(stationsParse, function(ob){
  Ext.Object.each(ob, function(property, value){
    console.log(property, value);
  });
});

Here I am using Ext.each to iterate over each element in the stationsParse array. Each element in that array is an object. To iterate over each property in the object I use Ext.Object.each. Both 'each' functions take the variable you want to iterate over as its first parameter and a function as its second parameter. The function will be run on each element of the array/property of the object.

Upvotes: 8

Andy
Andy

Reputation: 63550

If you want to use vanilla JS to loop over an array, a simple for loop will do the the trick. Access the value of each object's id4blob property using dot notation.

for (var i = 0, l = arr.length; i < l; i++) {
  console.log(arr[i].id4blob)
}

The for...in loop is generally reserved for looping over an object's properties.

Demo

Upvotes: 2

Related Questions