简体   繁体   中英

How to access the value of an object inside an array in JavaScript?

Here is my code.

var a = [   
    {
        name:"john",
        age:18,
        interests:[
            {
                uname: "computer",
                http: "google.com"
            },
            {
                lname:"foo",
                http: "twitter.com"
            }
        ]
    },
    {
        name:"jack",
        age:21,
        interests:["movies","music"]
    }
]

a.forEach(function(obj){
    for(var key in obj) {
        console.log(key)    
    }
})

How do I access the value of "uname"("computer") from the above code using the foreach loop?

Like this :

a.forEach(function(obj){
    for(var key in obj) {
        if (key == 'interests') {
            console.log(obj[key][0].uname);
        }
    }
})

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