[英]How to fetch an array object from json file
JSON: https://www.cc.puv.fi/~asa/cgi-bin/fetchOrders.py
我试图在 object 中获取对象和 arrays,但我只获取对象。
我如何获取“产品”arrays?
我的 javascript 代码:
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>';
}
您可能正在获取产品数组,但需要添加一些代码来迭代它。
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);
}
}
将循环中的控制台日志替换为一些代码以写入 html,就像您在上面所做的那样。 取决于您希望如何查看它可能会变得棘手,因此请考虑抽象出 HTML 代或使用可帮助您将 ui 组件化的库。
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
}
}
}
你已经遍历数组并从那里获取 object,如果你检查每个数组值(tialus.products)中都有产品数组,只需将该值保存在变量中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.