Home > Back-end >  rest api get an array of javascript objects
rest api get an array of javascript objects

Time:02-03

I am consuming this public api, the problem I have is that it is selecting an array of objects within the object field and I cannot access these values in the console, it shows me this (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

const url = https://catfact.ninja/facts;

    const getFact = () => {
    return fetch('https://catfact.ninja/facts' ,
    {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }})
    .then(res => res.json())
    }
    const createFactDiv = (fact) => {
        const factContainer = document.createElement('div');
        const setup = document.createElement('p');
      
        setup.innerText = fact.data
        console.log(fact.data);
        factContainer.append(setup);
      
        return factContainer
      }
    const appendFact = (factDiv) => {
    const factContainer = document.getElementById('factContainer');
    factContainer.append(factDiv);
    }

    //This is unused
    /*
    document.addEventListener('DOMContentLoaded', () => {
    })
    */

    getFact().then ((fact) => {
    const factDiv = createFactDiv(fact);
    appendFact(factDiv);
    })

enter image description here

CodePudding user response:

I think you're getting tripped up because getFact() is actually returning a result set that contains a number of (potentially useful) properties. It should probably be called getFacts(), because the .data property contains an array of multiple facts.

Perhaps try looping over the data array and setting setup.innerText to fact.fact rather than fact.data?

const getFacts = () => {
    return fetch('https://catfact.ninja/facts' ,
        {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }}).then(res => res.json())
    }

const createFactDiv = (fact) => {
    const factContainer = document.createElement('div');
    const setup = document.createElement('p');
  
    setup.innerText = fact.fact;
    console.log(fact.fact);
    factContainer.append(setup);
  
    return factContainer
  }

const appendFact = (factDiv) => {
    const factContainer = document.getElementById('factContainer');
    factContainer.append(factDiv);
}

//This is unused
/*
    document.addEventListener('DOMContentLoaded', () => {
    })
*/

getFacts().then(facts => facts.data.forEach(fact => appendFact(createFactDiv(fact))))

CodePudding user response:

console.log(JSON.stringify(fact.data));

CodePudding user response:

You can do a console.log(JSON.stringify(fact.data))

  •  Tags:  
  • Related