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