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

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

Utilizing fluent-ffmpeg in nodejs and express to effortlessly download a video

I've been recently tackling a side project that involves downloading videos from Reddit. The tricky part is that the video and audio are stored in separate files, requiring me to merge them before being able to download them onto the client's dev ...

Error encountered: The property 'localStorage' is not found on the 'Global' type

Calling all Typescript enthusiasts! I need help with this code snippet: import * as appSettings from 'application-settings'; try { // shim the 'localStorage' API with application settings module global.localStorage = { ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...

Learn how to define an array of member names in TypeScript for a specific type

Is there a way to generate an array containing the names of members of a specific type in an expression? For example: export type FileInfo = { id: number title ?: string ext?: string|null } const fileinfo_fields = ["id","ext&qu ...

Neglecting to utilize the document object within a React component results in the error "document is not defined."

I am utilizing browser detection code within a React component import React, { useState } from 'react' const BrowserDetectionComponent = ({props}) => { const isIE = document.documentMode; return ( <div> Custom browser s ...

Combining strings with JQuery

Looking for help with a code snippet <script> function goToDetails($i){ $(function(){ var transValue = $('#trans'+$i).html(); var mileageValue = $('#mileage'+$i).html(); var engineValue = $('#eng'+$i).html ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. Here is the code snippet: const InputBox = () => { const [value, ...

Is it feasible to utilize GraphQL subscriptions with Azure Functions?

Exploring the potential of implementing GraphQL subscriptions on Azure Functions. Unfortunately, it seems that apollo-server-azure-functions may not be compatible. Are there any other options or strategies to successfully enable this functionality? ...

What is the best way to conditionally wrap a useState variable in an if statement without losing its value when accessing it outside the if block in reactjs?

I am facing a coding challenge with my cards state variable in React using the useState hook. I tried adding my array data to it but ended up with an empty array. Placing the state inside an if statement resulted in undefined variables. I attempted various ...

Exploring the Live Search Functionality on an HTML Webpage

I am attempting to create a live search on dive elements within an HTML document. var val; $(document).ready(function() { $('#search').keyup(function() { var value = document.getElementById('search').value; val = $.trim(val ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

Can the keys of an object be retrieved in a specific order?

Is it possible to retrieve keys from a JSON object in the exact same order they were originally received? The use of Object.keys(company).length currently seems to be functioning, but I am seeking reassurance that this method will consistently deliver acc ...

Exploring the Fundamentals of XSS

Currently, my technology stack consists of Symfony2, Twig, and Doctrine. When it comes to securing my website, I am particularly concerned about preventing XSS attacks. However, despite taking precautions, I'm not sure what more I can do. Persisten ...

How do I use React and Material-UI to efficiently display multiple tables from a complex JSON object containing multiple arrays of data?

Trying to come up with an innovative approach to generate a unique dynamic table component that can create individual tables based on the number of arrays in a dictionary object (essentially iterating through each array and generating a table). For my sce ...

Tips for sending dynamic column and row information to antd table

The following code does not seem to work for an array containing rows and columns Below is an example using antd: const data = []; for (let i = 0; i < 4; i++) { data.push({ key: i, name: `Edward King ${i}`, age: 32 // address: `London ...

Activating the Speech Recognition feature in a form triggers the submission of a post

Currently, I am integrating webkitspeechRecongition into a form to allow users to enter data using their voice by pressing a button. However, a challenge arises when the call is triggered by a button within the form as it results in a post/submit action th ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

When utilizing JavaScript's split method, an empty string returns an array size of one instead of zero

Is there a way to separate a string using commas to create an array in Node.js? exports.test = function(rq, rs){ var mailList = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16657e7764777856627365623875797b">[email ...