If have the following data which I fetch from my NodeJS app and I want to show via javascript.
{
"holes": [{
"par": 5,
"strokeindex": 5
}, {
"par": 4,
"strokeindex": 15
}, {
"par": 3,
"strokeindex": 11
}, {
"par": 4,
"strokeindex": 13
}, {
"par": 4,
"storkeindex": 1
}, {
"par": 3,
"strokeindex": 17
}, {
"par": 4,
"strokeindex": 9
}, {
"par": 4,
"strokeindex": 7
}, {
"par": 4,
"strokeindex": 3
}, {
"par": 5,
"strokeindex": 6
}, {
"par": 4,
"strokeindex": 16
}, {
"par": 3,
"strokeindex": 13
}, {
"par": 4,
"strokeindex": 14
}, {
"par": 4,
"storkeindex": 2
}, {
"par": 3,
"strokeindex": 18
}, {
"par": 4,
"strokeindex": 10
}, {
"par": 4,
"strokeindex": 8
}, {
"par": 4,
"strokeindex": 4
}]
}
The data above is taken form the console where I have logged it with the following command:
console.log(JSON.stringify(data));
Now I want to output all the "par" information from each object in data.holes to a variable to show on my page. I have tried it in many ways like:
var html = "";
for(i = 1; i < 18; i++) {
html += data.holes[1].par + '<br/>';
}
And like this:
var html = "";
for(i = 1; i < 18; i++) {
html += JSON.stringify(data.holes[1].par) + '<br/>';
}
And like this:
var html = "";
for(i = 1; i < 18; i++) {
html += JSON.parse(data.holes[1].par) + '<br/>';
}
But when I do it this way I will get errors like 'Cannot read property "par" of undefined' or 'Uncaught SyntaxError: Unexpected token o '. Does somebody know what's wrong?
try
for (var i = 1; i < data.holes.length; i++) {
html += data.holes[i].par + '<br/>';
}
works for me check this fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.