2

Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});

This is the JSON:

{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}
2
  • 3
    Use < instead of <= in for loop condition. Commented Dec 7, 2017 at 8:52
  • Try to print the value of the variable, if you are getting fine or not. Commented Dec 7, 2017 at 8:55

3 Answers 3

3

You need to use < instead of <=.

Reason:-

Because jsonData.nameSearch indexs start from 0 like 0,1,.....so on

when you are using jsonData.nameSearch.length it gives you 2.

So loop will become:-

for (var j = 0; j <= 2; j++) {

but index 2 inside jsonData.nameSearch doesn't not exist at all. so you are getting error.

So the solution is removed = from loop like below:-

for (var j = 0; j < jsonData.nameSearch.length; j++)
Sign up to request clarification or add additional context in comments.

Comments

1

You need to remove = sign from for loop.

For loop should be like:

for (var j = 0; j < jsonData.nameSearch.length; j++)

Comments

1

Another approach could be something like this.

function nameSearchIdx(jsonData, idx, checkValue) {
    if (jsonData.nameSearch[idx].searchname === checkValue) {
        var linkname = jsonData.nameSearch[idx].namelink;
        alert(linkname);
    }
}
var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  Object.getOwnPropertyNames(jsonData.nameSearch).forEach(function (val, idx, array) {
     if(!isNaN(val)) {
         nameSearchIdx(jsonData, idx, selectedVal);
     }
   });
});

var jsonData = {
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
};
function nameSearchIdx(jsonData, idx, checkValue) {
if (jsonData.nameSearch[idx].searchname === checkValue) {
      var linkname = jsonData.nameSearch[idx].namelink;
      alert(linkname);
}
}
Object.getOwnPropertyNames(jsonData.nameSearch).forEach(
  function (val, idx, array) {
      if(!isNaN(val)) {
          nameSearchIdx(jsonData, idx, "calendar");
    }
  }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.