Reputation: 23
I find that the code works as I intended (I think). But the last step in which I print the data feels wrong. The way I concatenate the html and js seems abit off. Is there a better way to concatenate this? Am I using the wrong solution to print the data?
// This list I use inside my Array.
const myList = {
Germany : {name : 'Germany', capital: 'Berlin', visited: 'Checked' },
Italy : {name : 'Italy', capital: 'Rome', visited: 'Checked' },
Spain : {name : 'Spain', capital: 'Madrid', visited: 'unchecked' },
}
// My array
const destinations = [];
// Push data from myList to destination-array.
for(var key in myList) {
destinations.push(myList[key]);
}
// This is how write out my data on the page.
for (var i = 0; i < destinations.length; i++) {
document.write("<li><h1>" + destinations[i].name + "</h1><p>" +
destinations[i].capital +
"<input type='checkbox'" + destinations[i].visited + ">")
};
This Is what I am planing to write out at the end.
<li class="all-destinations">
<h3>destinations[i].name</h3>
<div class="container">
<label class="switch">
<input type="checkbox" destinations[i].visited>
</label>
</div>
<p>destinations[i].capital</p>
<hr>
</li>
Upvotes: 2
Views: 35
Reputation: 386634
You could assign the values to the innerHTML property directly without document.write
which may not work if the page is already full loaded.
function getItems({ name, capital, visited }) {
return `<li class="all-destinations">
<h3>${name}</h3>
<div class="container">
<label class="switch">
<input type="checkbox" ${visited}>
</label>
</div>
<p>${capital}</p>
<hr>
</li>`;
}
const myList = { Germany: { name: 'Germany', capital: 'Berlin', visited: 'Checked' }, Italy: { name: 'Italy', capital: 'Rome', visited: 'Checked' }, Spain: { name: 'Spain', capital: 'Madrid', visited: 'unchecked' } };
document.getElementById('list').innerHTML += Object.values(myList).map(getItems).join('');
<ul id="list"></ul>
Upvotes: 0
Reputation: 36574
You made your code better in three ways:
Object.values()
instead of creating []
and pushing to it.forEach()
rather than simple for loopsconst myList = {
Germany : {name : 'Germany', capital: 'Berlin', visited: 'Checked' },
Italy : {name : 'Italy', capital: 'Rome', visited: 'Checked' },
Spain : {name : 'Spain', capital: 'Madrid', visited: 'unchecked' },
}
const list = Object.values(myList);
list.forEach(x => {
document.write(
`<li class="all-destinations">
<h3>${x.name}</h3>
<div class="container">
<label class="switch">
<input type="checkbox" ${x.visited}>
</label>
</div>
<p>${x.capital}</p>
<hr>
</li>`)
})
Upvotes: 1