Как перебрать элементы сложного объекта и отобразить его в таблице

У меня есть классы Продукт и Магазин. Класс Product имеет свойства name, count и price.

class Product{
    constructor(name, count, price){
        this.name = name;
        this.count = count;
        this.price = price;
    }
}

class Shop{
    constructor(){
        this.arrProducts = [];
    }

    addProduct (Product) {
        let addName =  Product.name;
        let addPrice = Product.price;
        let addCount = Product.count;
        let newProduct = {name: addName, price: addPrice, count: addCount};

        return this.arrProducts.push(newProduct);
    };

}

Я создаю объект магазина и добавляю продукты

let shop = new Shop();

shop.addProduct(new Product("product1", 10, 200));
shop.addProduct(new Product("product2", 1, 500));
shop.addProduct(new Product("product3", 1, 1000));

После этого мне нужно отобразить все продукты в таблице. Я пытаюсь сделать это таким образом

let myTable= "<table><tr><td style='width: 100px; color: red;'>Product Name</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Price</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Count</td></tr>";

myTable+="<tr><td style='width: 100px;                   '>---------------</td>";
myTable+="<td     style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td     style='width: 100px; text-align: right;'>---------------</td></tr>";

for (let item in shop) {
    myTable+="<tr><td style='width: 100px;'>" + shop[item].name + "</td>";
    myTable+="<td style='width: 100px; text-align: right;'>" + shop[item].price + "</td>";
    myTable+="<td style='width: 100px; text-align: right;'>" + shop[item].count + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);

но я становлюсь неопределенным

2 ответа

Решение

Добавив в магазин метод, который возвращает список товаров, класс сам по себе не повторяется.

class Shop {
    getProducts() { return this.arrProducts; };
}

...
for (let item in shop.getProducts()) {
    // use item.name
    // item.price
    // item.count
}

Вы можете использовать массив продуктов напрямую, не используя новые объекты для информации о продукте.

Я предлагаю разделить информацию об одном продукте для таблицы и всей таблицы.

Если вам нужен какой-то стиль для строк, вы можете добавить некоторые классы CSS в строку или в заголовок таблицы.

class Product {
    constructor(name, count, price) {
        this.name = name;
        this.count = count;
        this.price = price;
    }
    getRow(cols) {
        var tr = document.createElement('tr');
        cols.forEach(key => {
            var td = document.createElement('td');
            td.classList.add(key);
            td.appendChild(document.createTextNode(this[key]));
            tr.appendChild(td);
        });
        return tr;
    }
}

class Shop {
    constructor() {
        this.products = [];
    }
    addProduct(product) {
        this.products.push(product);
    }
    getTable() {
        var table = document.createElement('table'),
            tr = document.createElement('tr');
        
        [['name', 'Product Name'], ['price', 'Price'], ['count', 'Count']].forEach(([key, text]) => {
            var th = document.createElement('th');
            th.classList.add(key);
            th.appendChild(document.createTextNode(text));
            tr.appendChild(th);
        });
        table.appendChild(tr);
        this.products.forEach(p => table.appendChild(p.getRow(['name', 'price', 'count'])));
        return table;
    }
}

let shop = new Shop();

shop.addProduct(new Product("product1", 10, 200));
shop.addProduct(new Product("product2", 1, 500));
shop.addProduct(new Product("product3", 1, 1000));

document.body.appendChild(shop.getTable());
td.name { width: 100px; }
td.count { width: 100px; text-align: right; }
td.price { width: 100px; text-align: right; }
th.name { width: 100px; color: red; }
th.count { width: 100px; color: red; text-align: right; }
th.price { width: 100px; color: red; text-align: right; }

Другие вопросы по тегам