Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
convert repeating code into function- JavaScript?

Am trying to bind values just to view. my code is working so far. but I'm repeating the same nested forEach 3 times. so Sonarcube will definitely mark it as duplicate. Could someone tell me how to avoid code repetition ?

Is there any way to optimize the below repeated codes and convert them as a generic function in JavaScript?

response.mainDish.forEach(element => {
    this.selectedMainDish.forEach(ele => {
        if (ele?.id === element.id) {
            this.bindMainDish.push(ele?.mainDish);
        }
    });
});

response.sideDish1?.forEach(element => {
    this.selectedSideDish1List.forEach(ele => {
        if (ele.id === element.id) {
            this.bindSideDish1.push(ele.sideDish1);
        }
    });
});

response.sideDish2?.forEach(element => {
    this.selectedSideDish2.forEach(ele => {
        if (ele.id === element.id) {
            this.bindSideDish2.push(ele.sideDish2);
        }
    });
});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can make a generic function using dynamic property names

let functionDoThis = function( mainDish , selectedMainDish, bindMainDish){
response[mainDish]?.forEach(element => {
    this[selectedMainDish]?.forEach(ele => {
        if (ele?.id === element.id) {
            this[bindMainDish]?.push(ele[mainDish]);
        }
    });
});

}

functionDoThis('mainDish', 'selectedMainDish' , 'bindMainDish');
functionDoThis('sideDish1', 'selectedSideDish1List' , 'bindSideDish1');

functionDoThis('sideDish2', 'selectedSideDish2' , 'bindSideDish2');

about 4 years ago · Juan Pablo Isaza Relatório

0

may besomething like that...

const dish_keys =
[ {dish:'mainDish',  selected:'selectedMainDish',      bind:'bindMainDish'  }
, {dish:'sideDish1', selected:'selectedSideDish1List', bind:'bindSideDish1' }
, {dish:'sideDish2', selected:'selectedSideDish2',     bind:'bindSideDish2' }
]


for (let {dish,selected,bind} of dish_keys)
  response[dish]?.forEach(element => 
    this[selected]?.forEach(ele =>{ 
      if (ele?.id === element.id)  this[bind]?.push(ele[dish]) }
  ) );
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda