Reputation: 23
i am destructuring an array to create html elements based on the data but i am finding a hard time figuring out how to remove the ',' after destructuring...
const elements = data.map((links) => {
const keys = Object.keys(links);
return `<div class="links"><p class="${keys[0]}">${links.website}</p>
<a href=${links.url} class="${keys[1]}">${links.userName}</a></div>`;
});
result:
<div class="links"><p class="website">Linkedin</p>
<a href="https://www.linkedin.com/in/andresilveira717" class="url">André Silveira</a></div> **,**
the ',' is appearing on the DOM, how do i remove it ?
I tried to destructuring it to a string but then i am not being able to create elements based on criteria.
Here is the data:
export const data = [
{
website: "Linkedin",
url: "https://www.linkedin.com/in/andresilveira717",
userName: "André Silveira"
},
{
website: "Github",
url: "https://github.com/the717q",
userName: "@the717q"
},
{
website: "Twitter",
url: "https://twitter.com/the717q",
userName: "@the717q"
}
];
Upvotes: 1
Views: 86
Reputation: 20821
When you are attempting to insert a HTML string into the DOM, ensure it is not an array of strings instead of a string. Otherwise you will see commas in the output (most likely due to Array.prototype.toString() being implicitly called on the array).
You can use elements.join('')
to get a html string of all the elements without commas in between them.
const data = [
{
website: "Linkedin",
url: "https://www.linkedin.com/in/andresilveira717",
userName: "André Silveira"
},
{
website: "Github",
url: "https://github.com/the717q",
userName: "@the717q"
},
{
website: "Twitter",
url: "https://twitter.com/the717q",
userName: "@the717q"
}
];
const elements = data.map((links) => {
const keys = Object.keys(links);
return `<div class="links"><p class="${keys[0]}">${links.website}</p>
<a href=${links.url} class="${keys[1]}">${links.userName}</a></div>`;
});
document.querySelector('#root').insertAdjacentHTML('beforeEnd', elements.join(''))
<div id="root"></div>
Upvotes: 2