0

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.

2
  • you can for one use string concatenation (you can use += operator). the other way i could think off, is just having append in the loop against the dom directly. Commented Jul 15, 2022 at 23:17
  • Does this answer your question? Concatenate string through for loop Commented Jul 15, 2022 at 23:19

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

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.