Undefined Variable
Undefined Variable

Reputation: 4267

iterate through objects and array javascript/angular

I am trying to iterate an object that I get in Angular but I was unable to. In order to understand that I tried it simply using below code:

<script>
var x = {"data":['A','B','C']};
for(v in x) 
{
    alert(v[0]);
}   
</script>

The output of this is "d".How can I output "A"?

Upvotes: 0

Views: 27

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

If you use this for loop, this is the syntax:

var x = {"data":['A','B','C']};
for(var key in x) 
{
    alert(key);    //data
    alert(x[key]); //A,B,C
}   

This is plain JS though, no Angular.

You can add further if clauses to receive the first element like A, but make sure it doesn't error out on other properties of the object.

Fiddle

Upvotes: 1

Related Questions