-2

How can I traverse through each element of array in javascript.

<script>
            var arrayCollection;
            $(function() {
                arrayCollection = [
                    {"id": "animal", "parent": "#", "text": "Animals"},
                    {"id": "device", "parent": "#", "text": "Devices"},
                    {"id": "dog", "parent": "animal", "text": "Dogs"},
                    {"id": "lion", "parent": "animal", "text": "Lions"},
                    {"id": "mobile", "parent": "device", "text": "Mobile Phones"},
                    {"id": "lappy", "parent": "device", "text": "Laptops"},
                    {"id": "daburman", "parent": "dog", "text": "Dabur Man", "icon": "/"},
                    {"id": "CN=dalmatian", "parent": "dog", "text": "Dalmatian", "icon": "/"},
                    {"id": "african", "parent": "lion", "text": "African Lion", "icon": "/"},
                    {"id": "indian", "parent": "lion", "text": "Indian Lion", "icon": "/"},
                    {"id": "apple", "parent": "mobile", "text": "Apple IPhone 6", "icon": "/"},
                    {"id": "samsung", "parent": "mobile", "text": "Samsung Note II", "icon": "/"},
                    {"id": "lenevo", "parent": "lappy", "text": "Lenevo", "icon": "/"},
                    {"id": "hp", "parent": "lappy", "text": "HP", "icon": "/"}
                ];}</script>

I had tried using for loop by takin gthe length and accessing element in loop as

arrayCollection[iterator]

but it just returns [Object, Object] Have also tried by type conversion but doesn't works.

Mr x
  • 828
  • 1
  • 8
  • 25

2 Answers2

2

You can do that by using forEach() method like so:

arrayCollection.forEach(function(v,i){
                          console.log(v.id)
                        })

where i = index and v = value, since the value is an object you can access it's properties directly.

-1

This works, I tested,

for (i in arrayCollection) {
       item = arrayCollection[i];
       console.log("id=" + item['id'] + ", parent="+item["parent"] + ", text=" + item['text']);
 }

output:

 id=animal, parent=#, text=Animals
 ....

For those not want to use "for..in" you can use index as well such as:

for (i=0;i<arrayCollection.length; i++) {
    item = arrayCollection[i];
    console.log("id=" + item['id'] + ", parent="+item["parent"] + ", text=" + item['text']);
}
JSBach
  • 447
  • 1
  • 6
  • 13
  • Why is a minus? Did I misunderstand the question? – JSBach May 13 '16 at 09:14
  • Maybe someone doesnt like your use of [`for...in` to traverse an array](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – Jamiec May 13 '16 at 09:17
  • Guy wanted to use such. That's why. He doesn't want the high level solution. He wants best suited solution as it seems. – JSBach May 13 '16 at 09:21
  • I mustve missed where the OP asked to treverse an array in the worst possible way. – Jamiec May 13 '16 at 09:28