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;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745470638a4629116.html
评论列表(0条)