简体   繁体   中英

Return specific value from nested object javascript

This is the object,

{
    "response": {
        "count": 49472,
        "items": [
            {
                "hello": "james",
                "title": "game",
                "player": "123",
                "home": "syd",

            }
        ]
    }
}

I would like to get a specific value from player and return 123 in the object using javascript. I have tried looking at other posts but I can't get it to work for my case.

I have managed to do this in python using the code below but it's not as simple to me with js.

for items in obj['response']['items']:
        print(items['player'])
var obj = var t = {
    "response": {
        "count": 49472,
        "items": [
            {
                "hello": "james",
                "title": "game",
                "player": "123",
                "home": "syd",

            }
        ]
    }
}

t.response.items[0].player
"123"

What you have is an object with an object which contains an array which contains an object . You can access it like so: myObject.response.items[0].player

(Run the code snippet to see the result)

 var myObject = { "response": { "count": 49472, "items": [ { "hello": "james", "title": "game", "player": "123", "home": "syd" } ] } }; console.log(myObject.response.items[0].player);

 var myObject = { "response": { "count": 49472, "items": [ { "hello": "james", "title": "game", "player": "123", "home": "syd" } ] } }; myObject.response.items.forEach((v) => { console.log(v.player) }); // or myObject.response.items.map(res => console.log(res.player)) // or console.log(myObject.response.items[0].player) //or console.log(myObject.response.items[0]['player'])

Would be something like this:

response.items.forEach(item =>
    console.log(item.player)
)

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