There is a JSON data and I have displayed each key value as a column in the table. I want to export data from JSON to each column as a selectbox. i.e. I want to show all corresponding values of “country” in JSON as selectbox in COUNTRY column.
My JSON data
"kitap": [ { "author": "Chinua Achebe", "country": "Nigeria", "imageLink": "images/things-fall-apart.jpg", "language": "English", "link": "https://en.wikipedia.org/wiki/Things_Fall_Apartn", "pages": 209, "title": "Things Fall Apart", "year": 1958 }, { "author": "Hans Christian Andersen", "country": "Denmark", "imageLink": "images/fairy-tales.jpg", "language": "Danish", "link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.n", "pages": 784, "title": "Fairy tales", "year": 1836 },
My Javascript
let table2 = document.getElementById("tr2") var books = fetch("kitap.json") .then(res=> res.json()) .then(veri => {for(let data in veri ) { for(deger of veri[data]) { select.innerHTML+= ` <td><option value="${deger.author}">${deger.author}</option></td> <td><option value="${deger.country}">${deger.country}</option></td> ` } }})
How can i edit?
Advertisement
Answer
Do you mean something like this? A loop over the keys, then a loop for all the items for each key. Finally after aggregating into array, we do a <select>
element using a simple utility function.
var obj = {"kitap":[{"author":"Chinua Achebe","country":"Nigeria","imageLink":"images/things-fall-apart.jpg","language":"English","link":"https://en.wikipedia.org/wiki/Things_Fall_Apartn","pages":209,"title":"Things Fall Apart","year":1958},{"author":"Hans Christian Andersen","country":"Denmark","imageLink":"images/fairy-tales.jpg","language":"Danish","link":"https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.n","pages":784,"title":"Fairy tales","year":1836}]} function do_select(select, options, name) { select.innerHTML = '<option>Choose ' + name + '</options>'; options.forEach(function(value) { var z = document.createElement("option"); z.setAttribute("value", value); z.innerText = value; select.appendChild(z) }) } do_obj_selects(obj) function do_obj_selects(obj) { var arr = obj.kitap; var keys = Object.keys(obj.kitap[0]); var result = {} keys.forEach(function(key) { obj.kitap.forEach(function(item) { result[key] = result[key] || [] result[key].push(item[key]) }) var sel_category = document.createElement("SELECT"); sel_category.setAttribute("id", "category"); document.body.appendChild(sel_category); do_select(sel_category, result[key], key) }) }