Home > Blockchain >  How to generate HTML text with a for loop?
How to generate HTML text with a for loop?

Time:07-16

I have a list of expenses, I want to create a html code to iterate over all the expenses and show their name. I am not working with the DOM, I literally want to save the html code in a variable, so I can generate a pdf file with it.

This is what I tried: lets say I have this array

const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]

    const testHtml = () => {
         for(let i of spents) {
            const title = `<h1>${i.expenseName}</h1>`
          }
        }
        testHtml()

This is the result I want, something like:

htmlResult = "<h1>${i.expenseName}</h1> <h1>${i.expenseName}</h1>"

by the way, This is for a react native app.

CodePudding user response:

I think this will work for you.

const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]

const testHtml = () => {
   let title = '';
   for(let i of spents) {
       title  = `<h1>${i.expenseName}</h1>`
   }
   return title;
}
testHtml()

CodePudding user response:

You could use Array.prototype.reduce().

const spents = [{
  expenseName: "Pizza"
}, {
  expenseName: "Home"
}];

const result = spents.reduce((prev, curr, index) => index === 0 ? curr.expenseName : `<h1>${prev}</h1> <h1>${curr.expenseName}</h1>`, '');

document.body.append(result);

  • Related