Loop through each object in an array and verify if the value matches a specific criteria in Javascript

Explore the common issues related to object iteration and queries outlined below.

Presented here is a list of objects (used for managing a connection form):

const connectionData = {
  mail: {
    value: false,
    isRequired: true
  },
  password: {
    value: false,
    isRequired: true
  },
  name: {
    value: false,
    isRequired: false
  },
}

Included below is an array variable that contains all the objects from connectionData

const fieldsToCheck = [connectionData.mail, connectionData.password, connectionData.name]

The intention of the check function below is to verify if:

For each object in fieldsToCheck where isRequired is true, if value is false, return true, otherwise, return false

const check = () => {
  if((fieldsToCheck.filter(key => 
    key.isRequired).every(val => 
        !val.value))) {
            return true
  } else {
    return false
  }
}

This function adequately serves its purpose. With the current object values, it returns true, and false if values are altered to true or ""

I pondered if there might be a quicker or more refined method of achieving the same outcome.

Wishing everyone a pleasant day ahead!

Answer №1

To achieve the desired outcome, consider switching from using .filter() to .every() directly on the fieldstocheck array. By doing so, you eliminate the creation of a new array in memory and reduce the number of iterations, as the array is only iterated through once:

const connexionData = { mail: { value: false, isRequired: true }, password: { value: false, isRequired: true }, name: { value: false, isRequired: false }, }

const fieldstocheck = [connexionData.mail, connexionData.password, connexionData.name];

const res = fieldstocheck.every((obj) => !obj.isRequired || !obj.value);
console.log(res);

Within the code snippet, the logic checks if isRequired is false with !obj.isRequired. If true, the .every() callback method returns true for that object. If isRequired is true, it then examines obj.value to determine its falseness: !obj.value.

From a propositional logic perspective, the condition:

!obj.isRequired || !obj.value

is equivalent to

!(obj.isRequired && obj.value)

(refer to De Morgan's law for further clarification). This alternative interpretation considers whether the object is required and contains a value, returning false, or otherwise, true (if it's not required or lacks a value).

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

Tips for including an additional label on a data point within a scatter plot using the Highcharts JavaScript framework

Incorporating the Highcharts JavaScript library, I am visualizing float values by passing them from PHP to the JS code. In the image below, you can observe that upon hovering over each point, the corresponding axes values are displayed along with the text ...

Troubleshooting a dysfunctional collapsed navbar in React with Bootstrap 5

I am experiencing an issue where the collapsed navbar icon does not expand when clicked on smaller screens. I followed the example provided by bootstrap 5 and made sure to include bootstrap css/js and jquery. class CustomNavBar extends Component { re ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...

The MUI Slide Transition experiences a malfunction when using multiple Slide components simultaneously

I'm having trouble getting the animations to work for each mui Slide when the button is clicked. It seems like they don't want to cooperate and work together. Oddly enough, if you disable one of the slides, the other one starts working fine, but ...

What are the key distinctions between an arrow function, a class, and a traditional function?

Is there a way to distinguish between the following three elements in ES6 using its reference? let x = i => i+1; class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} } function z(i) { return i+1; } For example: test(x) //=> ' ...

Incorporate the jquery lazy load plugin alongside ZURB foundation data-interchange for optimal performance

Currently, I am engaged in a project that involves utilizing the ZURB foundation framework alongside its data-interchange feature to display various images based on different screen sizes. To learn more about this method, please visit: You can also explo ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

Attempting to retrieve an element by its ID from a div that was dynamically loaded using AJAX

I am having trouble retrieving the value of an element with getElementById from a div that is loaded via ajax. Let me explain: In 'example.php' I have the following JavaScript code: <script type= "text/javascript"> var page=document.getE ...

What is the proper way to reference a property's value within another property of the same JavaScript Object?

Within a Gulp.js file (or any Javascript file), I have defined paths in a Javascript object: var paths = { devDir : 'builds/development/', devDirGlobs : this.devDir+'*.html' } I am attempting to reference the pro ...

What is the process for assigning one file input to another file input?

Quite an unusual question, I admit. The crux of the matter is my utilization of a fantastic tool known as cropit. With this tool, we have the ability to upload an image, preview it, and then manipulate it according to our preferences. HTML: <div align ...

Struggling to get a price calculator up and running efficiently

The code I have should be functioning, however, when I insert it into the code module in the Divi theme on WordPress, it doesn't work. Interestingly, when I try it in a notepad, it works perfectly fine but fails to function on the website itself. () ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

Tips on altering the location path when redirecting to a different page using window.location?

Is it a silly question to ask? I tried looking for the answer on Google but couldn't find it. I'm currently working on a website where users can upload photos or videos, using HTML, CSS, and JavaScript. On the homepage, when a user clicks on a ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Generate HTML on the fly using Node variables

Utilizing Node.js with Express as the server, I have implemented a feature where users can upload .CSV files containing data. This data is then parsed and stored in a main array made up of arrays, with each line representing one array element. Currently, I ...

What is the best way to style HTML content with MathJax following its retrieval with jQuery.load?

I recently encountered an issue while using jQuery.load to load a new page. The content on the original page is being treated strangely in some way. Specifically, I have code on the original page that formats LaTeX commands with MathJax: <script type=" ...

Complete interaction with child processes in Node.js

I have a basic C++ program compiled using the command gcc 1.cpp -o 1.exe. // 1.cpp #include <stdio.h> int main(){ int num = 0; scanf("%d", &num); printf("%d", num + 1000); scanf("%d", &num); printf("\n%d", num + 1000); ...

What process is involved in implementing TCO (Tail Call Optimization) for a recursive anonymous function in ES5?

Is there a way to optimize an anonymous recursive function for tail call optimization, similar to how a named recursive function can be optimized? If such a method exists, please provide explanations on how to achieve it. Below is an example of a recursi ...

Select a memory location within an Array at random?

Is it possible to randomly select a memory location in an Array without filling it up? I am looking for a way to do this, preferably using VB.NET. In terms of the logic, I was considering something like: Dim random As Random Dim arr(2, 2) As String rand ...