How to access all similar keys in all objects in a JSON array of objects?

I want to get all the keys called “name” in all of the 3 objects here and print their values, How can I do that ?

Expected output :

“Leanne Graham”, “Ervin Howell”, “Marina Howell”

[
    {
        "id": 1,
        "name": "Leanne Graham"

    },
    {
        "id": 2,
        "name": "Ervin Howell"
    },
    {
        "id": 3,
        "name": "Marina Howell"
    }
]

Do you know the various methods for iterating an array? There are several to choose from.

1 Like

That was very helpful, thank you

@bbsmooth How can I do the same if it’s a JSON object, not an array?

It’s an array of objects according to your post though?

1 Like

Yeah, it is, should I ask in another post ?

Are you asking about an array of objects or an object with objects inside of it?

Might be best if you paste in an example of the data structure you are asking about?

1 Like

@JeremyLT @bbsmooth I was trying to simplify my problem but I got confused, So here is the actual problem :

I’m trying to use the breaking bad API, I want to get episodes by season, the API doesn’t provide that option, So I want to get all seasons that has the same value

The API returns an array, but when I check its type, it prints “Object” and that made me confused, Here’s my code

I honestly can’t get that picture big enough to read on my phone. Copying the code and/or datastructures in directly would help a ton.

That API call is returning an array of objects. Just put https://www.breakingbadapi.com/api/episodes into your browser’s address bar and it will show you exactly what you are getting. So you would iterate through it like any other array.

2 Likes

Thank you for your help :heart:

That’s my code

fetch("https://www.breakingbadapi.com/api/episodes")
    .then((response) => {
        return response.json()
    })
    .then((data) => { return data })
    .then((data) => {
        console.log(data) 
/*  OUTPUT: 
Array(102) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ] 
        console.log(typeof data) //Output: Object
 */
    })

Got it! Thank you so much for your help :star_struck:

It’s an array, so any method for looping over an array would work. Then you can access the object properties of each array entry like you would any other object.

1 Like

Thank you so much for your help :blue_heart:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.