简体   繁体   中英

Double for loop multidimensional array javascript

Im using ajax to return some json. Here is what the json looks like.

[{"optionValue":"11","optionDisplay":"Canon","preitem":`[{"preitemId":"15","preitemLabel":"Canon EF 100mm f\/2.8L Macro IS USM "},{"preitemId":"18","preitemLabel":"12412"},{"preitemId":"21","preitemLabel":"Sonydas1df Test"}]},{"optionValue":"20","optionDisplay":"Nikon","preitem":""},{"optionValue":"21","optionDisplay":"Audio & Aerial","preitem":""},{"optionValue":"23","optionDisplay":"Sony","preitem":[{"preitemId":"19","preitemLabel":"Sony 1412Test"},{"preitemId":"20","preitemLabel":"Son124124y Test"}]}]`

From what you can see here each option has a few preitems.

For example Canon has the preitems Canon EF 100mm, 12412 and Sonydas1df Test.

The goal is to output everything onto a html page.

So canon will have its own heading with its pre items under it.

Here is my code.

for (var i = 0; i < j.length; i++) {
    for (var u = 0; u < j[i].preitem.length; u++) {
        preitems += j[i].preitem[u].preitemLabel+'<br>';
    }
options += '<div class="itemBlock"><b>'+ j[i].optionDisplay +'</b><input class="subcheckboxes" type="checkbox" id="checkit" value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</input><div class="" id="subcat' + j[i].optionValue + '">'+preitems+'</div></div>';

  }
$("#subcat").html(options);

The main options (canon,etc) get displayed fine. However it does not output the only the pritems which are in the option. It outputs every single preitem in the whole json returned.

I want to only show the preitems which are in the option.

Thanks

You aren't resetting preitems

You probably want...

for (var i = 0; i < j.length; i++) {
    preitems = '';
    for (var u = 0; u < j[i].preitem.length; u++) {
    ...

When traversing multi-dimensional data objects, you need more specifically identify which actions happen how many times and where. Your plan of just scooping up all of the pre-items and dumping them for each item is fine if you reset the pre-items as rjdown suggests. I'd try something like this instead though:

 for (var i = 0, lenj = j.length; i < lenj; i++) { options += '<div class="itemBlock"><b>'+ j[i].optionDisplay +'</b><input class="subcheckboxes" type="checkbox" id="checkit" value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</input><div class="" id="subcat' + j[i].optionValue + '">'; for (var u = 0, lenu = j[i].preitem.length; u < lenu; u++) { options += j[i].preitem[u].preitemLabel+'<br>'; } options += '</div></div>'; } $("#subcat").html(options); 

I feel like this is much more readable and fixes your problem.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM