JSON: https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py
Im trying to fetch objects and arrays within the object but im only fetching the objects.
How do i fetch also "products" arrays?
My javascript code:
fetch('https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py')
.then(res => res.text())
.then(teksti => tulostus(teksti))
function tulostus(txt) {
console.log(txt);
let tilaukset = JSON.parse(txt);
console.log(tilaukset);
let a = "<table><tr><th>orderid</th><th>customerid</th><th>customer</th><th>invaddr</th><th>delivaddr</th><th>deliverydate</th><th>respsalesperson</th><th>comment</th><th>totalprice</th></tr>";
for(let i = 0; i < tilaukset.length; i ) {
let tilaus = tilaukset[i];
console.log(tilaus)
console.log(tilaus.orderid);
a = '<tr><td>' tilaus.orderid '</td><td>' tilaus.customerid '</td><td>' tilaus.customer '</td><td>' tilaus.invaddr '</td><td>' tilaus.delivaddr '</td><td>' tilaus.deliverydate '</td><td>' tilaus.respsalesperson '</td><td>' tilaus.comment '</td><td>' tilaus.totalprice '</td></tr>'
}
console.log(a);
document.getElementById('info').innerHTML = a '</table>';
}
CodePudding user response:
You likely are fetching the products array but need to add some code to iterate over it.
for(let i = 0; i < tilaukset.length; i ) {
let tilaus = tilaukset[i];
console.log(tilaus)
console.log(tilaus.orderid);
a = '...'
for (let j=0; j < tilaus.products.length; j ) {
console.log(tilaus.products[i].name);
}
}
Replace the console log in the loop with some code to write to the html as you were doing above. Depending on how you'd like it to look at might get tricky, so consider abstracting away HTML generation or using a library that helps you componentize the ui.
CodePudding user response:
fetch("https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py").
then(response => response.json())
.then(result => display(result))
let display = (result) => {
for (let i = 0; i < result.length; i ) {
let products = result[i].products
// here products is a Object array
for(let i=0;i<products.length;i ){
let product = products[i];
console.log(product)
// add your stuff here like product.orderid to get orderid
}
}
}
CodePudding user response:
you're already looping over the array and getting the object from there, if you check there's product array there in every array value(tialus.products) just save that value in a variable