PDA

View Full Version : JSON: Why does each property show twice?



kayut
02-05-2017, 03:48 PM
Hi, looking at this example of Plunker:

http://plnkr.co/edit/z0bnxjV2XkBZC0yJxL7Z?p=preview

can some one please tell my why does each answer and each question coming from the JSON file show twice?

Thanks

jscheuer1
02-05-2017, 03:59 PM
I clicked on the link in your post and there's nothing there. Well it has a script with no code in it, no JSON file, and an HTML file that says only "Hello Plunker!"

But to try answering the question, I would guess that either you're fetching the JSON twice or have things listed twice in it. Or possible you're iterating over the retrieved JSON object twice.

kayut
02-05-2017, 04:19 PM
Sorry, I just updated the link. Now it works.

jscheuer1
02-05-2017, 04:54 PM
OK, what you're doing is iterating over the array , and each item (each i) gets gone over twice, once for each key. Change:


var result = '';
for (var i = 0; i <= data.length; i++) {
for (var key in data[i]) {
result += '<select class="my-select"><option>' + data[i].question + '</option></select>';
result += '<div class="my-div">' + data[i].answer + '</div>';
}
}

to:


var result = '';
for (var i = 0; i < data.length; i++) {
result += '<select class="my-select"><option>' + data[i].question + '</option></select>';
result += '<div class="my-div">' + data[i].answer + '</div>';
}

If you want to iterate both the array and its contained objects, this would work:


$(document).ready(function() {

$.getJSON('faq.json', function(data){
var tags = ['<select class="my-select"><option>', '</option></select>', '<div class="my-div">', '</div>'],
result = [], i = data.length, c = -1, t = tags.length;
while (--i > -1) {
for(var key in data[i]){
result.push(tags[++c % t] + data[i][key] + tags[++c % t]);
}
}

document.getElementById('container').innerHTML = result.join('\n');

}); //getJSON

// $('.my-select').on('click', function(e) {
// $(this).next(".my-div").slideToggle();
// });

}); // ready