Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over nested Json array

Tags:

json

arrays

New in json and js, so I would appriciate if someone would teach me a bit. Json array:

var info = [
{"t":"09:00","b":"Vaba"},
{"t":"09:30","b":"Vaba"}  ] ;

And JS part:

var output='';      
for (var i = 0; i <= info.length; i++) {
    for (info.t of info[i] ) {
        output += '<option> '  + info[i].t + ' ' + info[i].b + '</option>';  } };

    var update = document.getElementById('start_time');
    update.innerHTML = output;

The result I get in HTML looks like this:

<option>9.00 Vaba</option>
<option>9.00 Vaba</option>
<option>9.30 Vaba</option>
<option>9.30 Vaba</option> 

This is the only working solution I have found so far, but I don't need a double list (time and text string twice). Writing any function instead of second for loop ends with error info[i] undefined...

Thanks ahead.

like image 437
user2854901 Avatar asked Jun 14 '26 16:06

user2854901


1 Answers

Just remove your extra for loop. Also be careful about referencing an out-of-bounds index in info. When i = info.length, info[i] is out of bounds. Just make sure it never gets that far:

var output='';      
for (var i = 0; i < info.length; i++) {
    output += '<option> '  + info[i].t + ' ' + info[i].b + '</option>';  
}

var update = document.getElementById('start_time');
update.innerHTML = output;
like image 199
Bucket Avatar answered Jun 17 '26 23:06

Bucket



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!