I know this questions is asked several times but most answers are in plain javascript.
I have a function that creates an array with product data. That array is used in an other function to get new data via JSON.
$(function(){
var product_info = []
$('.prod').each(function(){
product_info.push({
id: $(this).data('pid'), amt: $(this).data('qty'), vid: $(this).data('vid'), url: 'some-url/'+$(this).data('pid')+'?secret=secret&quantity='+$(this).data('qty')
})
});
getId(product_info)
});
function getId(product){
var matched_variant = []
$.each(product, function(index, item) {
var vid = item['vid']
$.getJSON(item['url'], function(data){
$.each(data.variants, function(i, variant){
if(variant.id == vid){
matched_variant.push({
id: variant.id, dt: Number(variant.deliveryTimeInDays), dtt: variant.deliveryTime, co: variant.cutOffTime, sid: variant.supplier_id
})
}
});
});
});
console.log(matched_variant.length, matched_variant)
}
When I do a console.log matched_variant.length
it always shows 0
. But there are elemets in it as seen below (copied from console.log)
[
{
"id": 79380296,
"dt": 3,
"dtt": "in three days",
"co": "15:00",
"sid": 5
},
{
"id": 79380299,
"dt": 1,
"dtt": "same day",
"co": "17:00",
"sid": 5
}
]
Why does the length always equals zero then?
I've read that this could have something to do with asynchronyous
(??). But what should be done then? Creating some sort of success function?
Any help greatly appreciated!
Updated with data response
{
"id": 41853029,
"variants": {
"79380290": {
"id": 79380290,
"supplier_id": 5,
"on_stock": "no",
"levelLocal": 0,
"levelSupplier": 0,
"deliveryTime": "niet leverbaar",
"cutOffTime": "15:00",
"deliveryTimeInDays": -1
},
"79380293": {
"id": 79380293,
"supplier_id": 5,
"on_stock": "no",
"levelLocal": 0,
"levelSupplier": 0,
"deliveryTime": "niet leverbaar",
"cutOffTime": "15:00",
"deliveryTimeInDays": -1
},
"79380296": {
"id": 79380296,
"supplier_id": 5,
"on_stock": "supplier",
"levelLocal": 1,
"levelSupplier": 250,
"deliveryTime": "Voor 15:00 uur besteld, over 3 werkdagen in huis",
"cutOffTime": "15:00",
"deliveryTimeInDays": 3
},
"79380299": {
"id": 79380299,
"supplier_id": 5,
"on_stock": "supplier",
"levelLocal": 2,
"levelSupplier": 250,
"deliveryTime": "Voor 15:00 uur besteld, over 3 werkdagen in huis",
"cutOffTime": "15:00",
"deliveryTimeInDays": 3
}
}
}