for my current code renders coma, quotation marks between my list items, not sure what the issue please help.
I change the code to this for it to be easier to read: "null" in tinary operator works and changing it doesn't affect the problem or result. (currentCollection[indexOf item].Words are an array of words and regex = /[a-z]/g)
for (let i = 0; i < currentCollection.length; i ) {
let words = currentCollection[i].Words.join(" ")
elementsString = `<div><h2>${currentCollection[i].name}</h2>
<ul>
${currentCollection[i].Words.map(word => regex.test(word) ? (`<li>${word}</li>`) : null
)}</ul></div>`
CodePudding user response:
It looks like you're trying to do something like this. I'm not sure what that test
is meant to do so I left it out. But I added some CSS to make it look pretty.
const arr = [
{ id: 1, name: 'Alpaca', words:['a', 'b'] },
{ id: 2, name: 'Moose', words:['c', 'd'] },
{ id: 3, name: 'Tiger', words:['e', 'f'] },
{ id: 4, name: 'Sparrow', words:['g', 'h'] }
];
// `map` over the array of words to create a
// list of items
function getItems(words) {
return words.map(word => {
return `<li>${word}</li>`;
}).join('');
}
// `map` over the array to create a heading
// and a list of items in an unordered list element
const html = arr.map(obj => {
const { name, words } = obj;
return `
<div>
<h2>${name}<h2>
<ul>${getItems(words)}</ul>
</div>
`;
}).join('');
document.body.innerHTML = html;
h2 { font-size: 1em; }
ul { font-weight: 400; list-style: none; margin-left: 0; padding-left: 0; }
li { padding: 0.2em; margin-left: 0.5em; text-transform: uppercase; }
li:hover { cursor: pointer; background-color: #ffff00; }
Additional documentation