1

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"
  }
];
1
  • 1
    Your code example isn't complete. Please include the data and an example that can reproduce the problem that you're facing. Commented Feb 7, 2023 at 2:25

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Much appreciated, so simple... LoL !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.