Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Is there a way to combine the function body of this forEach funtion?

So I have this forEach function that replaces the text in a table cell after some data is submittied. I'm replacing three different table cells based on table row and I have those separated out into three different statements.

Like this:

replaceData.forEach((item, i) => {
  $(`.tableData tbody tr:eq(${item.index})`)
    .children(["td:eq(6)"])
    .text(values[i] === null ? "-" : values[i]);
  $(`.tableData tbody tr:eq(${item.index})`)
    .children("td:eq(7)")
    .text(reason[i]);
  $(`.tableData tbody tr:eq(${item.index})`)
    .children("td:eq(8)")
    .text(notes[i] === null ? "-" : notes[i]);
});

I tried combining those three statements like this, but this didn't work. Does anyone know how I can combine these three statements, if possible? Or is the only way to achieve this is by keeping them as their own statement?

$(`.tableData tbody tr:eq(${item.index})`)
  .children(["td:eq(6)", "td:eq(7)", "td:eq(8)"])
  .text([
    values[i] === null ? "-" : values[i],
    reason[i],
    notes[i] === null ? "-" : notes[i]
  ]);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Doing them separately looks like the correct thing to do, putting everything in 1 single line doesn't gain you anything, and loses lots in readability, especially when using lots of ternary operations.

But you could clean up your code here by just creating a reference to the row, instead of repeating it each time.

eg.

replaceData.forEach((item, i) => {
  const row = $(`.tableData tbody tr:eq(${item.index})`);                   
  row.children('td:eq(6)').text(values[i] === null ? '-' : values[i])
  row.children('td:eq(7)').text(reason[i]);
  row.children('td:eq(8)').text(notes[i] === null ? '-' : notes[i])
})

If you have lots of columns, you could even create a simple inline function to make things even easier to follow.

eg.

replaceData.forEach((item, i) => {
  const row = $(`.tableData tbody tr:eq(${item.index})`);                   
  const R = c => row.children(`td:eq(${c})`);
  R(6).text(values[i] === null ? '-' : values[i]);
  R(7).text(reason[i]);
  R(8).text(notes[i] === null ? '-' : notes[i]);
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!