Search code examples
javascriptarraysjsonfetchjavascript-objects

How do I find a specific object in a JSON array, and then console.log it?


So basically I am trying to receive the JSON from my API request, find the specific object in a specific array, and then print said object in the console. I just started learning JSON and JavaScript so if this is something that's as easy as cake don't be too harsh haha.

I am using fetch for my API requests, and essentially I have tried doing the same thing with an extremely simple API, which worked. But now that I'm using one that sends a boat-load of information back, I'm finding it difficult to access the specific array I need.

<script>
    fetch("https://some-random-api.ml/animal/dog")
                    .then(response => response.json())
                    .then(data => {
                        console.log(data.fact)
                        document.querySelector("#fact").innerText = data.fact
</script>
<h3 id="fact"></h3>

This API works, (test it if you would like, no auth needed, it's kinda cool) and when I use almost the exact syntax (switching out the data.fact for data.song (example) it always says undefined.

Now let's say this is my JSON return:

[
    {
        "name": "Big Corp",
        "NumOfEmployees": 10000,
        "ceo": "Mary",
        "rating": 4.6
    },
    {
        "name": "small startup",
        "NumOfEmployees": 4,
        "ceo": null,
        "rating": 4.5

    }
]

To allow the same syntax to be used, I found that you need to make a variable that contains all this JSON for it to recognize it.

let companies = [
    {
        "name": "Big Corp",
        "NumOfEmployees": 10000,
        "ceo": "Mary",
        "rating": 4.6
    },
    {
        "name": "small startup",
        "NumOfEmployees": 4,
        "ceo": null,
        "rating": 4.5

    }
]

From there I would do:

<script>
document.querySelector("#json").innerText = (companies)[1].name
</script>

<h3 id="json"></h3>

This method would work, but as stated earlier, if I'm receiving a new JSON object every time, I won't be able to do this (right?).


Solution

  • Have you tried to do this?

    <script>
        fetch("https://some-random-api.ml/animal/dog")
                        .then(response => response.json())
                        .then(data => {
                            document.querySelector("#json").innerText = data[1].name
                        })
    </script>
    <h3 id="json"></h3>
    

    Here, data is the name you gave to the JSON value you are receiving. If you expect to receive an array, you can use data as any other JavaScript array.