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
JavaScript
x
22
22
1
"kitap": [
2
{
3
"author": "Chinua Achebe",
4
"country": "Nigeria",
5
"imageLink": "images/things-fall-apart.jpg",
6
"language": "English",
7
"link": "https://en.wikipedia.org/wiki/Things_Fall_Apartn",
8
"pages": 209,
9
"title": "Things Fall Apart",
10
"year": 1958
11
},
12
{
13
"author": "Hans Christian Andersen",
14
"country": "Denmark",
15
"imageLink": "images/fairy-tales.jpg",
16
"language": "Danish",
17
"link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.n",
18
"pages": 784,
19
"title": "Fairy tales",
20
"year": 1836
21
},
22
My Javascript
JavaScript
1
14
14
1
let table2 = document.getElementById("tr2")
2
3
var books = fetch("kitap.json")
4
.then(res=> res.json())
5
.then(veri => {for(let data in veri ) {
6
for(deger of veri[data]) {
7
8
select.innerHTML+= `
9
<td><option value="${deger.author}">${deger.author}</option></td>
10
<td><option value="${deger.country}">${deger.country}</option></td>
11
`
12
}
13
}})
14
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.
JavaScript
1
32
32
1
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}]}
2
3
4
function do_select(select, options, name) {
5
select.innerHTML = '<option>Choose ' + name + '</options>';
6
options.forEach(function(value) {
7
var z = document.createElement("option");
8
z.setAttribute("value", value);
9
z.innerText = value;
10
select.appendChild(z)
11
})
12
}
13
14
do_obj_selects(obj)
15
16
function do_obj_selects(obj) {
17
18
var arr = obj.kitap;
19
var keys = Object.keys(obj.kitap[0]);
20
var result = {}
21
keys.forEach(function(key) {
22
obj.kitap.forEach(function(item) {
23
result[key] = result[key] || []
24
result[key].push(item[key])
25
})
26
27
var sel_category = document.createElement("SELECT");
28
sel_category.setAttribute("id", "category");
29
document.body.appendChild(sel_category);
30
do_select(sel_category, result[key], key)
31
})
32
}