I have this data and I'm displaying the name. But when I click on, in this case Sweden, I want to display additional info. In the code below I just want to display the country code, but this creates four additional <p> tags because of .forEach loop. That's not really what I want.
How would I go about if I just want to display the country code, and what if I wanted to display all the additional info? I'm kinda stuck as of now.
let data = [
{"name": "Swaziland", "code": "SZ"},
{"name": "Sweden",
"info": [
{"code": "SE"},
{"population": "10.2 million"},
{"area": "447 435km"},
{"capital": "Stockholm"},
{"Language": "Swedish"}]
},
{"name": "Switzerland", "code": "CH"},
{"name": "Syrian Arab Republic", "code": "SY"}
]
let output = '<ul class="searchresultCountries">';
let countries = data;
countries.forEach((value) => {
output += '<li>' + value.name + '</li>';
});
output += '</ul>';
document.querySelector('#countries').innerHTML = output;
document.addEventListener('click', (e) => {
data.forEach((item) => {
if(item.name === e.target.textContent) {
if(item.info) {
item.info.forEach((items) => {
let extraInfo = document.createElement("p");
extraInfo.textContent = items.code;
e.target.appendChild(extraInfo);
});
}
}
});
});
ul {
padding: 0;
}
.searchresultCountries li {
list-style-type: none;
border: 1px solid grey;
margin-bottom: 10px;
padding: 5px;
}
<div id="countries"></div>