Grafik Krystian
Grafik Krystian

Reputation: 231

Table creation in Javascript

I'm trying to create a specific table by communicating with the backend. I did not post the backend code, as it is not important here.

This is what all my code looks like:

JS :

const Api = function () {
    this.headers = new Headers({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    })
};

Api.prototype.buildUrl = function (id) {
    return "http://localhost:3000/db/games/" + id;
};


Api.prototype.post = function (id, data) {
    //const urlPost = api.buildUrl(id.value);
    const urlPost = this.buildUrl(id);
    return fetch(urlPost, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: this.headers
    }).then(this.handleResponse)
        .catch(this.handleError);
};


Api.prototype.get = function (id) {
    return fetch(id,
        {
            method: "GET",
        }
    )
        .then(resp => {
                alert(resp.json());
                return resp.data();
            }
        )
};
Api.prototype.getAll = function () {
    const urlPost = "http://localhost:3000/db/games";

    return fetch(urlPost,
        {
            method: "GET"
        }
    )
        .then(resp => {
            return resp.json()
        })
};

Api.prototype.update = function (id, data) {
    const url = api.buildUrl(id);
    return fetch(url,
        {
            method: "PUT",
            body: JSON.stringify(data)
        }
    )
        .then(resp => {
            return resp.json()
                .catch(error => {
                    let notFound = "The server can not find requested resource";
                    document.getElementById("stars").innerHTML = notFound + error.status;
                })
        })
};

Api.prototype.addProduct = function (id, data) {
    alert(id.value);
    alert(data.price.value);
    return this.post(id, data);
};

Api.prototype.deleteProduct = function (id) {
    return this.delete(id);
};

Api.prototype.updateProduct = function (id, data) {
    return this.update(id, data);
};

Api.prototype.getProduct = function (id) {
    return this.get(id);
};
Api.prototype.getAllProducts = function () {
    return this.getAll;
};

const Main = function () {
    this.addId = document.getElementById("id-add");

    this.addCount = document.getElementById("count-add");
    this.addName = document.getElementById("name-add");
    this.addPrice = document.getElementById("price-add");
    this.addPicture = document.getElementById("picture-add");

    this.editId = document.getElementById("id-edit");

    this.editCount = document.getElementById("count-edit");
    this.editName = document.getElementById("name-edit");
    this.editPrice = document.getElementById("price-edit");
    this.editPicture = document.getElementById("picture-edit");

    this.addBttn = document.getElementById('postBtn');
    this.editBttn = document.getElementById('editBtn');

    this.updateBttn = document.getElementById('updateBtn');
    this.deleteBttn = document.getElementById('deleteBtn');
    this.getBttn = document.getElementById('getBtn');
    this.getAllBttn = document.getElementById("getAllBtn");
};


Main.prototype.add = function () {
    const ido = this.id.value;
    const data = {
        "price": this.addPrice.value,
        "name": this.addName.value,
        "count": this.addCount.value,
        "picture": this.addPicture.value,
    };
    api.addProduct(ido, data);
};

Main.prototype.update = function () {
    const data = {
        "price": this.price,
        "name": this.name,
        "count": this.count,
        "description": this.description,
        "picture": this.picture
    };
    api.updateProduct(id, data);
};


Main.prototype.delete = function () {
    let id = api.buildUrl(this.id);
    api.deleteProduct(id);
};


Main.prototype.get = function () {
    let id = api.buildUrl(this.id.value);
    api.getProduct(id);
};


Main.prototype.getAll = function () {


//    api.getAllProducts();


};


Main.prototype.makeList = function () {

api.getAll().then(data => {

// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');

// retrieve column header ->> does not works
let col = [];
for (let i = 0; i <  data.length; i++) {
    for (let key in data[i]) {
        if (col.indexOf(key) === -1) {
            col.push(key);
        }
    }
}
let tHead = document.createElement("thead");
let hRow = document.createElement("tr");
for (let i = 0; i < col.length; i++) {
    let th = document.createElement("th");
    th.innerHTML = col[i];
    hRow.appendChild(th);
}
tHead.appendChild(hRow);
table.appendChild(tHead);
 let tBody = document.createElement("tbody");

for (let i = 0; i < data.length; i++) {
    let bRow = document.createElement("tr");

    for (let j = 0; j < col.length; j++) {
        let td = document.createElement("td");
        td.innerHTML = data[i][col[j]];
         bRow.appendChild(td);
    }
    tBody.appendChild(bRow)

}
table.appendChild(tBody);

let divContainer = document.getElementById("list");
divContainer.innerHTML = "";
divContainer.appendChild(table);

});

};

const main = new Main();
const api = new Api();

main.addBttn.addEventListener('click', main.add.bind(main));
main.getAllBttn.addEventListener('click', main.makeList.bind(main));

HTML : Shop SHOP

    </div>
    <div class="admin">
        <a href="shop.html"> ADMIN </a>

    </div>
</div>


<div class="rectangle">
    <div class="add">
        <div class="form-title">
            Add new products
        </div>
        <form class="input-row">
            <label for="id-add">Id:</label>
            <input type="number" name="id" id="id-add">
            <label for="count-add">Count:</label>
            <input type="text" name="count" id="count-add" placeholder="Name">
            <label for="name-add">Name:</label>
            <input type="text" name="name" id="name-add" placeholder="Name">
            <label for="price-add">Price:</label>
            <input type="number" name="price" id="price-add" placeholder="Price">
            <label for="photo-add">Photo:</label>
            <input type="text" name="photo" id="photo-add" placeholder="Photo">
        </form>
        <button class="m-bttn" id="postBtn">add</button>
    </div>

    <div class="edit">
        <div class="form-title">
            Edit products
        </div>
        <form class="input-row">
            <label for="id-edit">Id:</label>
            <input type="number" name="id" id="id-edit">
            <label for="count-edit">Count:</label>
            <input type="text" name="count" id="count-edit" placeholder="Name">
            <label for="name-edit">Name:</label>
            <input type="text" name="name" id="name-edit" placeholder="Name">
            <label for="price-edit">Price:</label>
            <input type="number" name="price" id="price-edit" placeholder="Price">
            <label for="photo-edit">Photo:</label>
            <input type="text" name="photo" id="photo-edit" placeholder="Photo">
        </form>
        <button class="m-bttn" id="editBtn">show items in stock</button>
    </div>
</div>

<div class="delete">
    <div class="form-title">
        Delete
    </div>
    <form class="input-row">

        <label for="id-delete">Id:</label>
        <input type="number" name="id-delete" id="id-delete">
    </form>
    <button class="m-bttn" id="deleteBtn">del</button>
</div>
<button class="m-bttn" id="getAllBtn">edit</button>

<div id="list"></div>
</div>


</div>

<script src="script.js"></script>

</body>
</html>

Console.log from my fetch-API:enter image description here

By this code I have getting : enter image description here

The question is how can I modify my code to get such data in columns?

Data should be -> price

Id should be -> count

Name should be -> name

Upvotes: 1

Views: 57

Answers (1)

Jan
Jan

Reputation: 2249

In case you do not mind hardcoding .data reference, anyway you need a translation structure (array there to be able to set order). You can change code like this.

const data =
JSON.parse(prompt('Paste or edit JSON data:', JSON.stringify([{
    _id: 323,
    _rev: 'something',
    data: {
        count: 5,
        name: 'kotek',
        price: 23
    }
},
{
    _id: 3231,
    _rev: 'something',
    data: {
        count: 6,
        name: 'kotek',
        price: 23
    }
}])));
var table = document.createElement('table');
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');

// retrieve column header ->> does not works
const header = ['data', 'id', 'name'];
const col = ['price', 'count', 'name'];
const tHead = document.createElement('thead');
const hRow = document.createElement('tr');
for (let i = 0; i < header.length; i++) {
    const th = document.createElement('th');
    th.innerHTML = header[i];
    hRow.appendChild(th);
}
tHead.appendChild(hRow);
table.appendChild(tHead);
const tBody = document.createElement('tbody');

for (let i = 0; i < data.length; i++) {
    const bRow = document.createElement('tr');

    for (let j = 0; j < col.length; j++) {
        const td = document.createElement('td');
        td.innerHTML = data[i].data[col[j]];
        bRow.appendChild(td);
    }
    tBody.appendChild(bRow);
}
table.appendChild(tBody);

const divContainer = document.getElementById('list');
divContainer.innerHTML = '';
divContainer.appendChild(table);
<div id="list"></div>

Another option is general traverse, but also needed translation info from source to desired output.

Upvotes: 1

Related Questions