MY JSON is:
[
{
"id": "5d7d855c-7301-4b2f-9676-3cb758316b4c",
"products": [
{
"id": 1,
"price": 699.0,
"quantity": 2,
"color": "silver",
"size": "128GB"
}
],
"contact": {
"name": "5423654",
"surname": "gdfsgsdf",
"address": "gfdsg",
"phone": "53454353",
"city": "5234532",
"country": "gfdsgfds"
},
"shippingPrice": 0.0,
"discount": null,
"totalPrice": 1398.0
}
]
I am trying to loop in it with for loop in
class Orders {
_orders;
constructor() {
this.init().then(() => this.renderOrders());
}
async init() {
this._orders = await this.getOrders();
}
GET(url) {
try {
return axios.get(url)
} catch (e) {
return e;
}
}
getOrders() {
return new Promise(resolve => {
this.GET('http://localhost:8080/orders/getOrders').then(response => {
resolve(response.data);
})
})
}
renderOrders() {
const template = document.getElementById("orders__template");
const container = document.getElementById("orders");
container.innerHTML = "";
console.log(typeof this._orders);
for (let key in this._orders) {
if (this._orders.hasOwnProperty(key)) {
for (let productKey in this._orders[key].products) {
if (this._orders[key].products.hasOwnProperty(productKey)) {
console.log(this._orders[key].products[productKey].id); //getting the id
}
}
for (let discountKey in this._orders[key].discount) {
if (this._orders[key].discount.hasOwnProperty(discountKey)) {
console.log(this._orders[key].discount[discountKey].id); //undefined(even when it's not null, why?
}
}
for (let contactKey in this._orders[key].contact) {
if (this._orders[key].contact.hasOwnProperty(contactKey)) {
console.log(this._orders[key].contact[contactKey].name); //undefined too
}
}
}
}
}
document.addEventListener("DOMContentLoaded", () => {
new Orders();
});
However, i am getting only at first for loop result, other discount, or contact are undefined. i tried with other dummy data, i am getting the same results, so, what is the problem? However, i have other examples where it do work, the same structure, whats wrong?
this._ordersthe array or the object?productsis an array of object whereascontactis an object. The last loop, loops over the properties (name,surnameetc.), not over the array items.