M
M
Mark2021-07-04 17:55:36
JavaScript
Mark, 2021-07-04 17:55:36

How can I shorten the record of creating identical elements?

Multiple tds are added to tr . Here's how it's written now:

function createPayment({id, sum, system, date})
{
    const payment = document.createElement('tr');
    payment.classList.add('item', 'block-sr-2', 'all');
    payment.dataset.ref = "mixitup-target";

    const addPaymentCell = value => {
        const td = document.createElement("td");
        td.innerText = value;
        return td;
    };

    payment.append(addPaymentCell(id));
    payment.append(addPaymentCell(sum));
    payment.append(addPaymentCell(system));
    payment.append(addPaymentCell(date));
}


It seems to me that it can be shortened somehow by using the loop correctly so as not to duplicate:
payment.append(addPaymentCell(id));
    payment.append(addPaymentCell(sum));
    payment.append(addPaymentCell(system));
    payment.append(addPaymentCell(date));


In fact, you can use foreach. But you have to re-create the object, setting the variables: id, sum, system, date. Or to refuse destructuring assignment in function arguments (or to carry out it later).

function createPayment({id, sum, system, date}) {
    const payment = document.createElement('tr');
    payment.classList.add('item', 'block-sr-2', 'all');
    payment.dataset.ref = "mixitup-target";

    const object = {id, sum, system, date};
    object.forEach(value => {
        const td = document.createElement("td");
        td.innerText = value;
       payment.append(td);
    });
}


Is it possible to somehow cleanly enumerate the variables to create a loop bypass on them?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-04
@MarkLb

We remove the destructuring of the parameter (well, or you can leave it, then the quotes from the array elements will need to be removed ( 'id'-> id, 'sum'-> sum, ...), and instead paymentData[n]it will be just n), instead of ten lines we write three:

payment.innerHTML = [ 'id', 'sum', 'system', 'date' ]
  .map(n => `<td>${paymentData[n]}</td>`)
  .join('');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question