admin管理员组文章数量:1426929
I have a JS method that takes a JSON file and try to get information out of it:
getData(json) {
var output = '';
json.Legs.forEach(function (item) {
.
.
.
.
.
.
});
return output;
}
I am getting this error for forEach:
Uncaught TypeError: Cannot read property 'forEach' of undefined
Is it possible to use forEach like this or I shouldn't be using forEach at all? Is there nother way to do this?
I have a JS method that takes a JSON file and try to get information out of it:
getData(json) {
var output = '';
json.Legs.forEach(function (item) {
.
.
.
.
.
.
});
return output;
}
I am getting this error for forEach:
Uncaught TypeError: Cannot read property 'forEach' of undefined
Is it possible to use forEach like this or I shouldn't be using forEach at all? Is there nother way to do this?
Share Improve this question asked Feb 6, 2018 at 8:41 karan kalimikaran kalimi 231 gold badge1 silver badge10 bronze badges 3-
2
error is pretty much clear, you do not have data within
json.Legs
. – Jigar Shah Commented Feb 6, 2018 at 8:43 - JSON by definition does not have arbitrary properties as it is just a string. Do you mean a JavaScript object instead or do you pass a string? How do you call that function? – str Commented Feb 6, 2018 at 8:44
- You need to run each loop after checking only if json.Legs is not null. e.g if(!json.Legs){ json.Legs.forEach(function (item) { . . . . . . }); } – Abdul Qayyum Commented Feb 6, 2018 at 8:45
3 Answers
Reset to default 2You need to execute loop after confirming that json.Legs
is not null. e.g
if(json.Legs){
json.Legs.forEach(function (item) {
.
.
.
.
.
.
});
}
Add this as the first line in the code and see what it prints. If it is an array you can all forEach
on it. Otherwise it's throwing the right error.
console.log(json.Legs)
Something like this should do the trick (check whether .legs property exists and whether its an array before iterating):
getData(json) {
var output = '';
if(json.Legs && Array.isArray(json.Legs)){
json.Legs.forEach(function (item) {
//do something with item
});
}
return output;
}
本文标签: javascriptCannot read property 39forEach39 of undefined in reactjs applicationStack Overflow
版权声明:本文标题:javascript - Cannot read property 'forEach' of undefined in reactjs application - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745470638a2659732.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论