Search code examples
javascripthtmlarraysfetch

How to enter inside array number - js


When I do a fetch, as response, I recieve a array list, with numbers, and inside those numbers, are the content, but I don't now how to enter inside those numbers, and, when I'm not inside the numbers, my li, mapped with the array content, goes like: [Object, object]

Response array

This image show the response array

My code piece:

fetch(`https://api.dicionario-aberto.net/suffix/${suffixValue}`)
    .then(res => res.json())
    .then(suff => {

        const suffixRes = document.getElementById('suffixRes')

        console.log(suff)
        
        var str = '<ul>'
        
        suff.forEach(function(objects) {
            str += '<li>'+ objects + '</li>';
        });

        document.getElementById("suffixRes").innerHTML = str;
    })

Solution

  • You need to look at the properties of the object you fetch. Something like this, perhaps:

    const suffixValue = 'cana'
    
    fetch(`https://api.dicionario-aberto.net/suffix/${suffixValue}`)
        .then(res => res.json())
        .then(suff => {
    
            const suffixRes = document.getElementById('suffixRes')
    
            // console.log(suff)
            
            var str = '<ul>'
            
            suff.forEach(function(object) {
                // maybe do something with "sense" too
                str += `<li>${object.word} (${object.preview})</li>`;
            });
    
            str += "</ul>"
    
            document.getElementById("suffixRes").innerHTML = str;
        })
    <div id="suffixRes" />

    When you talk about the "numbers", that's simply the indices of the array, shown in console as numbers. The point is that you have an array, an ordered collection of values. The values are what's important, and you already deal with the fact that they're in an array by calling forEach on it. Now you just need to handle the multi-property object included.

    But it might be nice to look at simplifying this as well. forEach is only rarely the appropriate solution. Here you have a list of items and want to turn it into a list of <li>-wrapped strings. That's better expressed with map. With some additional clean-up, that might end up looking like this:

    const suffixValue = 'cana'
    
    fetch(`https://api.dicionario-aberto.net/suffix/${suffixValue}`)
        .then(res => res.json())
        .then(res => 
            document.getElementById('suffixRes').innerHTML = 
              '<ul>' +
              res.map (({word, preview}) => `<li>${word} (${preview})</li>`).join('') +
              "</ul>"
         )
    <div id="suffixRes" />