Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function json() returns an Object with an array inside, I want an array of objects

I’m using Fetch to get data from a json server and save it in the connection constant. After getting the data, I use connection.json() to transform the json into a javascript object. But I can’t map this object, because it is an Object with an array inside. I would like to turn it into an array of objects. How should I proceed?

  useEffect(() => {
    list();
  }, [ ]);

  async function list(){
    try{
      const connection = await fetch("https://my-json-server.typicode.com/priscilasilvaalves/priscilasilvaalves.github.io/db");
      const list = await connection.json();
      setItems(list);
      console.log(items); // Returns an Object with an array inside
    }catch(error){
      console.log(error);
    }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the response contains the node lista. If you access it directly, you will get the desired result.

async function list(){
  try{
    const connection = await fetch("https://my-json-server.typicode.com/priscilasilvaalves/priscilasilvaalves.github.io/db");
    const list = await connection.json();
    setItems(list.lista); // Access the 'lista' property directly
    console.log(items);
  }catch(error){
    console.log(error);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading