Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. Despite not being null or undefined, some arrays contain objects and are mistakenly added even when their length is 0. Here's what I have tried so far:

var progressCount = 0;
var progressKeyLength = progressBarCriteria.length;
for (var i = 0; i<progressKeyLength; i++){
  //Although I can identify arrays at this point, I struggle to check their length due to them being object arrays.
  if(Array.isArray(progressBarCriteria[i])){
    console.log('array' + i);
  }
  if (progressBarCriteria[i] !== null && progressBarCriteria[i] !== ""){
    ++progressCount
  }
}


progressBarCritiria = [
   example1: "",
   example2: "asdasdas",
   example3: 233,
   example4: {asda: 1},
   example5: {asadasda: "asdasdA"},
   example6: "",
   example7: [],
   example8: [1, 12312],
   example9: [{1: "ad"}, {1: 12312}],
]

Hence, elements 1, 6, and 7 should be excluded from the count.

Answer №1

In order to verify the length or null value of an array, consider the concept of Truthy and Falsy values as detailed in this resource.

if (Array.isArray(progressBarCriteria[i]) && progressBarCriteria[i].length) {
   // This indicates that the array is not empty.
}
  • The statement
    Array.isArray(progressBarCriteria[i])
    ensures that the value is indeed an array.
  • If progressBarCriteria[i].length equals 0, the boolean value will be false; otherwise, it will be true.

Answer №2

If you want to accomplish this task, consider using a recursive function. Keep in mind that in javascript, arrays are treated as objects. Therefore, it is necessary to verify if an element is an object by using

if (typeof arr === 'object' && !(arr instanceof Array))
. For more details, refer to this page and this one.

function checkRecursiveArray(arr) {

  // Check if arr is an object
  if (typeof arr === 'object' && !(arr instanceof Array)) {
    
    // Check if the object is empty
    if (Object.keys(arr).length === 0) {
    
      // Perform an action if empty
      console.log('This object is empty');
    
    } else {
    
      // Recursively check object properties
      for (var key in arr)
        if (arr.hasOwnProperty(key))
          checkRecursiveArray(arr[key])
    
    }
  
  } else
  if (Array.isArray(arr)) {
  
    // Check if the array is empty
    if (arr.length === 0) {
    
      // Perform an action if empty
      console.log('This array is empty');
    
    } else {
    
      // Recursively check array elements
      for (var i = 0; i < arr.length; i++)
        checkRecursiveArray(arr[i])
    
    }
  
  }   

}

Answer №3

After reviewing both solutions, I have crafted a solution that works perfectly. Please note that this code snippet is written in Typescript.

for (let i = 0; i < progressKeyLength; i++){
  if (!(progressBarCriteria[i] instanceof Array)){
    if(progressBarCriteria[i] !== null && progressBarCriteria[i] !== "") {
        ++progressCount
    }
  } else {
    let current = progressBarCriteria[i];
    if (Array.isArray(current) && current.length !== 0){
      ++progressCount
    }
  }
}

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

Inquiry regarding the implementation of DTO within a service layer parameter

I have a query regarding the choice of service layer to use. // 1 export class SomeService{ async create(dto:CreateSomeDto) {} } or // 2 export class SomeService{ async create(title: string, content: string) {} } It appears that most individuals opt ...

What exactly does a 'hoisted manifest' mean when it comes to using Yarn?

Encountering an issue while attempting to install a package using yarn, I am receiving the error message: expected hoisted manifest for \"myPackage#@material-ui/core#react-dom\" However, the concept of a 'hoisted manifest' is not entir ...

Is there a way to prevent IntelliJ from creating .js files when working with .ts source code?

Working on a mixed Java/Typescript project with Maven as the build tool, I utilize the frontend-maven-plugin to successfully build from the command line. However, I am encountering an issue with IntelliJ 2018.2 where it keeps transpiling .js files for my . ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

After the execution of the script by V8, which phase will be initiated first?

Scenario // test.js setTimeout(() => console.log('hello'), 0) setImmediate(() => console.log('world')) Simply execute node test.js using node v12.12.12 on an Intel MacBook Pro. The output may vary: hello world Sometimes it is: ...

`Optimizing bundle size in Webpack using braintree-web integration with TypeScript`

When utilizing braintree-web 3.61.0 with Vue.js 2.6.11 and TypeScript 3.8.3, I organize the necessary components of braintree-web into a service in this manner: import { client, hostedFields, applePay } from 'braintree-web'; export default { cli ...

Steps for resetting data() on a route without parameters:

Having trouble restarting a route on a new editor I have a specific route /editor as well as /editor?_id=dasd448846acsca The /editor route consists of a simple form with empty inputs, while the /editor?_id=dasd448846acsca route has the same component bu ...

Endless rotation with stunning magnification feature

My goal is to create a responsive carousel with auto-play infinite loop functionality, where the center item always occupies 70% of the viewport width. Currently, I have achieved a similar result using the Slick library: https://codepen.io/anon/pen/pBvQB ...

Is it possible to verify the user's authentication by confirming the presence of a JWT in their localStorage?

I am currently working on a project that requires JWT authentication. I have set up a registration form and login page where users receive an authorityToken and it is saved in localStorage. Once the user logs into their account : ` $("#btnLogin").click( ...

The styling of a CSS class in Internet Explorer may not be applied correctly if there are multiple elements sharing the same class name

For nearly a full week now, I've been plagued by a persistent issue! Here's the situation: I have 6 step tabs - step 1, step 2, and so on. Each tab has a CSS class called "locked" and "active." "Locked" - this style features top: 3em;, causing ...

Using Thymeleaf in a Spring Boot application, the modal automatically closes after submission

How can I keep the modal open when I click the submit button? I want to reload an existing modal form when I click submit. The code form is in fragment/header, and when I click the "login" button, the modal shows up. The issue is that in views/loginForm, ...

Opt for JavaScript DOM manipulation over jQuery for element selection without depending on jQuery

I am attempting to target a specific element using JavaScript: element = '<div class="c-element js-element">Something Here</div>'; When I try to select this element with the following code: $(element) The result is not as expected ...

Single-select components in React Native

I am currently working on implementing a simple single selectable item feature, illustrated in the image provided below. https://i.stack.imgur.com/U2rJd.png At this moment, I have set up an array containing my data items and utilized the .map function to ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

Transforming PHP Variable Using Ajax

I have a variable called $type and I need it to be either month or year. This change should occur when a div is clicked. I attempted to use an onclick event with an ajax call. The ajax call and the variable are both in the same script (index.php). Within ...

What prevents us from returning Observable.of(false) in the catch block within the canActivate function?

In order to protect certain routes (admin), I utilize the canActivate feature. In this scenario, I employ an authGuard class/function: The issue arises when attempting to return an observable of boolean using: return Observable.of(false);. This approach d ...

Having difficulty accessing certain code in TypeScript TS

Struggling with a TypeScript if else code that is causing errors when trying to access it. The specific error message being displayed is: "Cannot read properties of undefined (reading 'setNewsProvider')" Code Snippet if (this.newsShow != ...

What are the essential files needed in Kendo UI Core for a mobile app?

Several months ago, I created a trial Kendo mobile app but now I want to verify it using the most recent version of Kendo UI Core. In my previous project, I referenced the following files: <link href="../styles/kendo.common.min.css" rel="stylesheet" / ...

Is there a way to define an object's keys as static types while allowing the values to be dynamically determined?

I am attempting to construct an object where the keys are derived from a string union type and the values are functions. The challenge lies in wanting the function typings to be determined dynamically from each function's implementation instead of bei ...

Tips for passing certain optional parameters while excluding others without resorting to undefined or empty values like ""

Is there a way to invoke the function while omitting certain optional parameters without resorting to undefined and empty strings? import { MouseEvent } from "react"; import { DialogType } from "editor-constants"; export interface Dial ...