简体   繁体   中英

loop two arrays from json

$.each([data.bahan,data.detail], function (i, value) {
   $("select.bahan_asli").clone().insertAfter("#bahan:last").val(value[0].id_bahan).append("<input type='hidden' value='" + value[1].id_detail + "'>");  
});

The Json code :

{
    "bahan": [{
        "id_bahan": "4",
        "nm_jenis": "katun"
    }, {
        "id_bahan": "1",
        "nm_jenis": "katun"
    }],
    "detail": [{
        "id_detail": "5",
        "id_model": "3"
    }, {
        "id_detail": "6",
        "id_model": "3"
    }]
}

I tried this code. This json from my php script (create json by array to json ). What's wrong with this code? How to call value[0].id_bahan and value[1].id_detail ?

In this case each is not working for what you want. I would go with a for loop, when bahan and detail are always the same length.

for( var i = 0; i < data.bahan.length; i++ ) {
    $("select.bahan_asli").clone()
                          .insertAfter("#bahan:last")
                          .val(data.bahan[i].id_bahan)
                          .append("<input type='hidden' value='" + data.detail[i].id_detail + "'>");
}

You can use each in a bit other way for it too, if you want:

$.each(data.bahan, function(i, bahan) {
    $("select.bahan_asli").clone()
                          .insertAfter("#bahan:last")
                          .val(bahan.id_bahan)
                          .append("<input type='hidden' value='" + data.detail[i].id_detail + "'>");
})

Working example.

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