1

How can I render JavaScript objects to HTML with pure JavaScript or jQuery?

data = {
  'this-is-title-123' : {
    title : 'this-is-title-123',
    content : 'Lorem ipsum dolor sit amet',
    date : '12.8.2009'
  },
  'this-is-title-456' : {
    title : 'this-is-title-456',
    content : 'the quick brown fox jumped',
    date : '18.2.2028'
  },
  'this-is-title-789' : {
    title : 'this-is-title-789',
    content : 'the jumped fox fell in a pit',
    date : '19.12.2020'
  }
}

I want to convert it to HTML like this:

<div>
  <h1>this-is-title-123</h1>
  <p>Lorem ipsum dolor sit amet</p>
  <p>12.8.2009</p>
</div>
<div>
  <h1>this-is-title-456</h1>
  <p>the quick brown fox jumped</p>
  <p>18.2.2028</p>
</div>
<div>
  <h1>this-is-title-789</h1>
  <p>the jumped fox fell in a pit</p>
  <p>19.12.2020</p>
</div>
3
  • what is the desired result? Commented Dec 16, 2020 at 14:38
  • <div> <h1>this-is-title-123</h1> <p>Lorem ipsum dolor sit amet</p> <p>12.8.2009</p> </div> <div> <h1>this-is-title-456</h1> <p>the quick brown fox jumped</p> <p>18.2.2028</p> </div> <div> <h1>this-is-title-789</h1> <p>the jumped fox fell in a pit</p> <p>19.12.2020</p> </div> this is what i want, sorry i dont know how to format text here, im new to stackoverflow, and i adde the desired output to question Commented Dec 16, 2020 at 14:46
  • welcome to SO, please go to stackoverflow.com/tour . SO is not a free code provider, you have to show some code you try first, and we try to help you to make it better Commented Dec 16, 2020 at 18:37

1 Answer 1

1

It can be as simple as iterating over the object values and updating the inner HTML.

const data = {
  'this-is-title-123': {
    title: 'this-is-title-123',
    content: 'Lorem ipsum dolor sit amet',
    date: '12.8.2009',
  },

  'this-is-title-456': {
    title: 'this-is-title-456',
    content: 'the quick brown fox jumped',
    date: '18.2.2028',
  },

  'this-is-title-789': {
    title: 'this-is-title-789',
    content: 'the jumped fox fell in a pit',
    date: '19.12.2020',
  },
};

const posts = Object.values(data).map(post => `
  <div>
    <h2>${post.title}</h2>
    <p>${post.content}</p>
    <time>${post.date}</time>
  </div>
`)

document.querySelector('#root').innerHTML = posts.join('\n');
body {
  font-family: sans-serif;
}
<div id="root"></div>

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

1 Comment

This does allow for XSS attack

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.