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

What is the best way to make a request to the deployed API on Vercel?

Here is the structure of my files: root client index.js package-lock.json package.json routes.js Upon sending a request to my API, I receive a status code of 200 but an error message stating "You need to enable JavaScript to run this app." Both ...

Submitting data to a PHP script using AJAX and the $_POST method

I'm attempting to transfer data from my AJAX request into a PHP $_POST variable in order to update my database. HTML <form id="23" method="post"> <select name="admin" onchange="chosenadmin(23)"> <option value="rick">rick&l ...

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

The processing-js library threw a Reference Error indicating that the Navigator could not be found

I am looking to utilize processingJS as an npm package in a nodeJS server for deployment on MS Azure. I am using VS15 and encountering difficulties referencing it: var pjs = require('processing-js'); var http = require('http'), fs = r ...

What is the best method for clearing all session cookies in my React application?

Currently, I am working on a project using React. I am trying to find a method to automatically logout the user by deleting all of the session cookies in my React application. However, I have not been able to come up with a solution yet. Is there a way to ...

Using a toolbar to insert a hyperlink for hypertext communication

My journey with Javascript and React began this week, so I'm still getting the hang of things, especially in the front end domain. In my project, there's a link button within a toolbar. The idea is to click on it, have a text box pop up where yo ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

Ways to merge two select options in a form

I'm attempting to merge the selections from two dropdown menus in a form into one variable before submitting the form. Here is an overview of my code: In new.html.erb (for RoR): <%= form_for :character, url: characters_path, method: :post do |f| ...

How can I stop iOS mobile browsers from automatically opening apps when I click on links?

Recently, I discovered an issue with my website when accessed on mobile (iOS). The links to external websites, such as Amazon product links, are causing the Amazon app to open instead of simply opening a new tab in the browser. The HTML code for these lin ...

Checking authorization with CognitoUser solely for "code" provided by CognitoUser (npm: amazon-cognito-identity-js)

Currently, I am in the process of implementing the "forget password" feature. However, I have encountered an issue where I would like to verify the "verification code" first before setting a new "password". Unfortunately, the system currently requires bo ...

Is it possible to use combox to deactivate the buttons?

My goal is to deactivate the button as soon as I select a value from the drop-down list. For example, here's what I have: <select name =""> <option> disable </option> <option> enable </option> </select> <input ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

The functionality of CSS3 animations may sometimes be unreliable following the onLoad event

Here is a snippet of code to consider: $(function() { $('#item').css({ webkitTransform: 'translate(100px, 100px)' }); }); The element I am attempting to move has the following CSS properties: transform: translate3d(0 ...

Functionality similar to ngChange, but applied to the entire form

Is there a way to create an equivalent of the ng-change directive for the entire form, triggering when any input field changes? I am aware of the debounce option in AngularJS 1.3, but it only works for individual inputs. I need a "debounce" or "on change ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Canvas displaying inaccurately (unsteady)

While working on a simple HTML5/javascript game, I encountered an unusual issue with the canvas drawings - they seem to be unstable. I have a map that needs to be drawn in a specific way: The background consists of 2 layers: the ocean and the islands. Th ...

Bootbox Dialog Form

Looking to implement a functionality where a Bootbox dialog pops up with an "OK" button. Upon clicking the "OK" button, it should initiate a POST request, sending back the ID of the message to acknowledge that the user has read it. The Bootbox dialog fun ...