How can I convert duplicate code into a function in JavaScript?

I have successfully bound values to a view in my code, but I am concerned about the duplicate nested forEach loops that are currently present. I anticipate that Sonarcube will flag this as redundant code. Can anyone advise me on how to refactor this to avoid repetition?

Is there a way to optimize the following repetitive sections and consolidate them into a generic JavaScript function?

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

Answer №1

If you want to create a flexible function that uses dynamic property names, here's how:

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

}

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

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

Answer №2

could look something similar to this...

const meal_keys =
[ {meal:'breakfast',  chosen:'chosenBreakfast',      binding:'bindBreakfast' }
, {meal:'lunch',      chosen:'chosenLunchList',      binding:'bindLunch'     }
, {meal:'dinner',     chosen:'chosenDinner',         binding:'bindDinner'    }
]


for (let {meal,chosen,binding} of meal_keys)
  response[meal]?.forEach(item => 
    this[chosen]?.forEach(chosenItem =>{ 
      if (chosenItem?.id === item.id) this[binding]?.push(chosenItem[meal]) }
  ) );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance User Experience with Dynamic Scroll Page Transition

Hey everyone! I've been working on revamping a website and stumbled upon this fascinating page transition that I would love to replicate. However, I haven't been able to find a JQuery library that can achieve this effect. Does anyone have any i ...

What is the process for assigning variables to modules using RequireJS?

Is there a way to define variables for modules in RequireJS? In simpler terms, how can I achieve the equivalent of the following using RequireJS: var fs = require('fs'); var child_process = require('child_process'); I am looking to s ...

Learn how to verify changing form inputs with Vue watchers. The challenge of numbers

Currently, I am working on a sum application and encountering some challenges with input validations. I have implemented Watcher to handle the validations, and I am exploring the possibility of adding sound and color feedback for accurate validation. Repo ...

Why are my cursor and my drawing line on opposite sides?

I've been working on a JavaScript drawing app, but I'm facing an issue where the drawn elements are not aligned with my cursor. The positioning seems off, especially when moving to the right or up on the canvas. As I move towards the furthest lef ...

Creating customized npm package.json scripts for each individual console command

When running npm install <module> --save, the module is added to the package.json, which can be quite convenient. In the package.json, there is a section dedicated to scripts. It would be helpful to have a command that automatically adds scripts her ...

Using JSDoc to Include TypeScript Definitions

I've been attempting to utilize the ts-xor package, which provides a TypeScript definition: export declare type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U; This is how I'm imp ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

The term 'components' has not been defined (no-undef)

Recently integrated Vue into an existing project and encountered a peculiar linting error: error: 'components' is not defined (no-undef) at src/App.vue:13:3: 11 | 12 | @Component({ > 13 | components: { HelloWorld }, | ^ 14 | }) ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

Remove option from MUI Autocomplete after it has been selected

I am currently utilizing a Material-UI Autocomplete component. To avoid users selecting the same element twice, resulting in duplicate ID numbers, I want to remove the element from the dropdown entirely. For instance, if "Shawshank Redemption" is selected ...

What are the steps to successfully submit my form once all the validation requirements have been met?

I successfully completed the validation process, but I am encountering an issue when trying to submit the form. An error message pops up indicating that there is an error related to a specific field (e.g., special characters being used). However, even when ...

Whenever I attempt to trim my integer within a for loop, my browser consistently becomes unresponsive and freezes

I am facing an issue with my code that generates alcohol percentage, resulting in values like 43.000004 which I need to trim down to 43.0, 45.3, etc. However, whenever I try to use any trim/parse functions in JavaScript, my browser ends up freezing. Below ...

What is the best way to add a style to the currently active link on a NavLink component using the mui styled() function

I have a custom NavLink component that I want to style with an ".active" class when it is active. However, I am not sure how to achieve this using the "styled()" function in MUI. Does anyone know how to accomplish this? Below is the code for my custom Nav ...

Having trouble installing @angular/cli 4 on Debian?

I'm having trouble installing @angular/cli on my Debian box. I already have the latest versions of Node.js and npm installed. Interestingly, Angular4 works perfectly fine on my Windows machine where I use it daily. However, when I try to get it runnin ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Having trouble loading the JSON data for display

My select dropdown is supposed to display the names of states. The data is being fetched from PHP and is also available in the controller JS file. However, the data is showing up as blank in the HTML. When I use console.log(), the fetched result from PHP s ...

The features of findOneAndRemove and findOneAndUpdate are not functioning optimally as expected

Attempting to create a toggle similar to Facebook's "like" feature. The code functions correctly when there are no existing "likes." It also deletes properly when there is only one "like" present. However, issues arise when multiple likes accumulat ...