TypeError: data.map is not a function

Poporingus picture Poporingus · Sep 9, 2018 · Viewed 10.9k times · Source

Im really stuck on this figuring out what did I miss, Im not that expert about javascript, if someone can please tell me what I did wrong, I really appreciate.

I have a working code:

if (value_ == "group") {
  fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
  .then(json => {
      var data =  `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
      var data = JSON.parse(data); 
      var groupName = data.group.map(current => current.name);
      var groupTag = data.group.map(current => current.tag);
      console.log(data);         
      console.log(`json: ${data.group[0].name}`);
    });
}

the code above will work and get every data I wanted, but the json is from the:

var data =  `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;

then I tried to get the json from the URL which return the same value as the var data above. But it doesn' work.

which I did change var data = JSON.parse(data); into data = JSON.parse(json)

and delete "var data = { "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] };"

And it does give an error: (node:10868) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input

I also tried this code:

  fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
  .then(json => {
      parseJSON(JSON.stringify(json));
      function parseJSON(str){
        var data = JSON.parse(str); 
        var groupName = data.group.map(current => current.name);
        var groupTag = data.group.map(current => current.tag);
        console.log(data);         
        console.log(`json: ${data.group[0].name}`);
      }

    });
}

this give me error: (node:12668) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined.

Thanks and pardon my english.

Answer

Oleksandr Kovpashko picture Oleksandr Kovpashko · Sep 9, 2018

You don't need to execute JSON.parse manually because the content of json variable in the third line of your example is already an object.

Try this:

fetch("http://localhost/someapi"+value_)
.then(r => r.json())
.then(json => {
  var groupName = json.group.map(current => current.name);
  var groupTag = json.group.map(current => current.tag);
  console.log('groupName', groupName);         
  console.log('groupTag', groupTag);         
});