Accessing a value via key in json is throwing undefined

user3205921 Source

Hello I am facing a weird error, i have a below object

    let dataFromUrl =  {
      "careerTrackId": 510,
       "country": [],
       "geography": [18],
       "ou2": [51549564],
       "ou3": [],
       "ou4": [],
       "ou5": [],
       "ou6": [],
       "ou7": [],
       "ou8": [],
       "region": []
    } 

console.log(dataFromUrl.geography.length);


// Here in this method iam using this dataFromUrl

   

     function getGeoUnitId(dataFromUrl) {
    console.log("dataFromUrl",dataFromUrl);
  console.log("dataFromUrl.geography",dataFromUrl.geography);
  console.log("dataFromUrl.ou2",dataFromUrl.ou2);
  console.log("dataFromUrl.careerTrackId",dataFromUrl.careerTrackId);
      let geoUnitId = "(" + dataFromUrl.geography + ")";
      let str2 = "geounitid IN " + geoUnitId;
      if (dataFromUrl.geography.length == 0) {
        str2 = "";
      }
      return str2;
    }

But when i am trying to use dataFromUrl.geography.length in my nodejs code, i get below error:

[ 'TypeError: Cannot read property 'length' of undefined']

This code was running when my target was es5 bu as soon as i changed the target to es6 it's starting to break. Does any1 have any idea why this suddenly started happening.

javascriptjsonnode.jstypescript

Answers

answered 1 week ago gandhi_rahul #1

After going through the comments, my possible guess is that you are calling the getGeoUnitId() without arguments and it's using the getGeoUnitId defined outside which you might have changed.

Try rename the arguments variable name

function getGeoUnitId(somethingOtherThan_dataFromUrl) {

Tip: If you are having a problem understanding the JS code, you should use the Chrome's (or any other browser) developer tools and add a debugger to see the flow of the code, how variables are being assigned values, where they are updated and so on...

answered 1 week ago user3205921 #2

Finally, i was able to fix it, i still don't know why but this worked : JSON.parse() did the trick.

let dataFromUrl =  {
      "careerTrackId": 510,
       "country": [],
       "geography": [18],
       "ou2": [51549564],
       "ou3": [],
       "ou4": [],
       "ou5": [],
       "ou6": [],
       "ou7": [],
       "ou8": [],
       "region": []
    } 


  function getGeoUnitId(dataFromUrl) {
    console.log("dataFromUrl",dataFromUrl);
  console.log("dataFromUrl.geography",dataFromUrl.geography);
  console.log("dataFromUrl.ou2",dataFromUrl.ou2);
  console.log("dataFromUrl.careerTrackId",dataFromUrl.careerTrackId);
      let geoUnitId = "(" + dataFromUrl.geography + ")";
      let str2 = "geounitid IN " + geoUnitId;
      if (dataFromUrl.geography.length == 0) {
        str2 = "";
      }
      return str2;
    }

 dataFromUrl = JSON.parse(dataFromUrl );
 console.log(dataFromUrl.geography.length); // this started giving me 1

comments powered by Disqus