search

Home  >  Q&A  >  body text

Map function does not work with received JSON (error: Uncaught (in promise) TypeError: datas.map is not a function)

Call method DataTable(config); //Everything is normal

Then load JSON, function fetchers(apiUrl) //Everything is normal

Then print the JSON I received on the console //Everything is fine

Then I tried to use Array.prototype.map() (before that I was using local data) and then I got this error....

Uncaught (in promise) TypeError: datas.map is not a function

DataTable(config);

const config = {                                       //ok
    parent: '#usersTable',
    apiUrl: "https://mock-api.shpp.me/mmykola/users"
};

async function fetchUsers(apiUrl) {                    //ok
    const response = await fetch(apiUrl);    
    return await response.json();
}

sync function DataTable(config) {
    let newData = await fetchUsers(config.apiUrl);    //ok
    console.log(newData["data"]);                     //ok

    newData.map((value) => {/*work with JSON create code for new table...../*});   //error here 
}

Before this, I used local data and created a table from it, everything was fine, but in the downloaded JSON, this happens.

I would be happy to get suggestions about this error, not just a solution,

Please also read the advice about json objects not having function type properties

and try to deconstruct a json object like this

const {data} = newData;
    console.log(data);  // 一切正常,简单的对象数组

 data.map((value) => {/*work with JSON...../*});//错误与上述相同

P粉419164700P粉419164700437 days ago615

reply all(1)I'll reply

  • P粉310931198

    P粉3109311982023-09-19 15:52:19

    So from the api response, you don't have an array, but an object.

    {
      "data": {
        "1": {
          "name": "Kylie",
          "surname": "Wiegand",
          "avatar": "https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/85.jpg",
          "birthday": "2022-08-07T08:37:37.367Z"
        },
        ...

    So you need to iterate through all properties in the data object. You can use Object.values() to convert all property values ​​into arrays and then use the map method.

    async function fetchUsers(apiUrl) {                    
        const response = await fetch(apiUrl);    
        return await response.json();
    }
    
    async function DataTable(config) {
        let newData = await fetchUsers(config.apiUrl);                 
        const x = Object.values(newData.data).map((value) => { return value; });
        console.log(x.length);   
    }
    
    const config = {                                       
        parent: '#usersTable',
        apiUrl: "https://mock-api.shpp.me/mmykola/users"
    };
    
    (async function () {
      await DataTable(config);
    })();

    reply
    0
  • Cancelreply