简体   繁体   中英

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"?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM