Looking to optimize the JavaScript code for improved performance speed

Is there a more efficient way to avoid writing the same lines of code repeatedly without compromising performance? I've attempted using a for loop to categorize fields as 'mandatory' or 'optional', but it still requires duplicating the loop. Can this be achieved in a more streamlined manner while maintaining performance?

    //mandatory
obj.required['test1' + number] = true;
obj.visible['test1' + number] = true;
obj.required['test2' + number] = true;
obj.visible['test2' + number] = true;
obj.required['test3' + number] = true;
obj.visible['test3' + number] = true;
//optional
obj.visible['test4' + number] = true;
obj.visible['test5' + number] = true;

Attempted solution with for loop:

var mandatoryField = ['test1', 'test2', 'test3'];
var optionalField = ['test4', 'test5'];

for(var i=0; i<mandatoryField.length; i++) {
obj.required[madatoryField[i] + number] = true;
obj.visible[madatoryField[i] + number] = true;
}

Answer №1

Do you have the ability to modify the field structure?

const obj = {
  visible: {
    test1: false,
    test2: false,
    test3: false,
    test4: false,
    test5: false,
    test6: false,
    test7: false,
    test8: false,
  },
  required: {
    test1: false,
    test2: false,
    test3: false,
    test4: false,
    test5: false,
    test6: false,
    test7: false,
    test8: false,
  },
};
const fields = [
  { field: 'test1', required: true },
  { field: 'test2', required: true },
  { field: 'test3', required: true },
  { field: 'test4' },
  { field: 'test5' },
];

fields.forEach(({ field, required }) => {
  const key = field; // `${field}${number}`;

  obj.visible[key] = true;

  if (required) {
    obj.required[key] = true;
  }
});

console.log(obj);

Answer №2

Implementing a solution like this can streamline the process into a single iteration.

var requiredFields = ['field1', 'field2', 'field3'];
var optionalFields = ['field4', 'field5'];

const counter = new Array(Math.max(requiredFields.length, optionalFields.length)).fill(0);
counter.forEach((item, index) => {
    if(requiredFields[index]) {
        obj.required[requiredFields[index] + number] = true;
        obj.visible[requiredFields[index] + number] = true;
    }
    if(optionalFields[index]) {
        obj.visible[optionalFields[index] + number] = true;
    }
})

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

The Node.js execSync functionality is not functioning as expected, as the changes made to the system are not taking effect

I'm looking to prevent chrome.exe from accessing the internet through the Windows firewall. The specific command I need to use is netsh advfirewall firewall add rule name="Block Chrome" dir=out action=block program="C:\Program Files (x86)\G ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...

Issue encountered with NextJS where the post request utilizing Bcrypt is not being recognized

In the process of developing a basic login feature using nextJS, I have successfully managed to save new usernames and encrypted passwords from the registration page. The login functionality is intended to be similar, but requires comparing the password st ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Update the state of the parent component based on changes made in the child component (both are functional

Here is the layout for the current issue: . ├── components │ ├── ModalPolicy.js │ ├── Footer │ ├── index.js ├── pages │ ├── index.js I attempted to display the Modal on Footer/index.js but it did no ...

What is the best way to ensure that two Node processes do not insert duplicate database records when running concurrently?

My Lambda function receives a high volume of events simultaneously, causing AWS to spin up multiple instances to handle the load. The function written in Node.js uses Knex to interact with a Postgres database, checking if a record with a specific ID exists ...

Issues with reactivity are present in certain items within Vue.js cards

Can someone please assist me with this issue that has been causing me trouble for days? I am working on updating the quantity and total price in a checkout card: The parent component: <template> <div> <upsell-checkout-product ...

Using Regular Expression to verify the presence of numbers and spaces

Currently, I have implemented a regular expression that ensures my string contains 5 digits. While this regex works flawlessly, I now also require it to allow white spaces: both "123 45" and "12345" should meet the criteria. string.match(/^\d{5}$/g); ...

Ways to adjust the color of a cell in a table

I am working on customizing a table in my website where I need to change the color of a single cell in each row, similar to the example shown in this image: Here is the HTML code that I have implemented so far: <table class="table table-hover t ...

Ways to invoke a next.js api that implements next-auth programmatically

In my next.js app, I have integrated next-auth which is set up to allow authentication using Facebook and Google as providers. Additionally, there are some endpoints located in the pages/api folder of the app. These endpoints are accessed from standard ne ...

The issue with jspdf is that it is failing to generate PDF documents of

I'm currently developing a resume builder app using ReactJS. One of the functionalities I'm working on is enabling users to download their resumes as PDFs. However, I've encountered an issue with the generated PDFs when using jsPDF. The down ...

Encountering the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" while using Django and Vue on my website

While working on my project that combines Vue and Django, I encountered a persistent error message when running the code: "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yel ...

Chrome not triggering the fullscreenchange event

I've been attempting to track when the browser goes into fullscreen mode. Everywhere I look, this blog is mentioned as the go-to resource on the fullscreen API. According to this SO answer, it should work. Fullscreen API: Which events are fired? B ...

React Router malfunctioning on production environment when integrated with an Express backend

My Single Page application is built using React for the frontend and Express for the backend. Within the application, there are two main components: and . The goal is to display the component when the "/"" URL is requested, and show the component for an ...

Click Action on CanJS Table

I am currently developing a canJS application and have been able to successfully handle the click event for an HTML table using the code below. 'table td click':function(el,event){ console.log('clicked ',el.text()); } ...

Transforming the NavBar in React: A guide to dynamically updating values

I am facing an issue with my NavBar that changes based on certain events. The current setup works fine, but I don't want to render it in every class that loads a new page. Initially, I had the NavBar rendering inside App.js so it could appear on all p ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Is there a live password verification tool available?

Currently, I am conducting some initial research for my school's IT department as a student employee. The students at our institution are required to change their passwords every six months, but many of them struggle with the various password regulati ...

Angular-Loopback-SDK: The method prototype$updateAttributes is not functioning as expected

I'm currently utilizing the loopback-angular-sdk and encountering a strange error while using the updateAttributes function: MyModel.prototype$updateAttributes is not a function This issue seems to be affecting all models. I have a hunch that it mig ...

Issue encountered while attempting to start npm: Error code from NPM

I keep encountering the npm ENOENT error every time I attempt to execute npm start. I am unsure of what steps to take in order to resolve this issue. I have made efforts to adjust folder permissions. bryantcaruthers-> npm start npm ERR! code ENOENT npm ...