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

Caution: Potential Unresolved Promise Rejection Detected (ID: 21) - Error: Undefined is not a valid object when trying to evaluate 'res.json'

ERROR Getting an Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json'). Any suggestions on fixing this issue in my code? I've checked the logs for user and loggeduserobj, and they seem to be cor ...

Uncovering the Mystery Behind the Repetitive Execution of useEffect in Next.js

I am working on a Time Tracking feature for my Next.js application. In the ./app/components/TimeTracking.tsx file, I have implemented the following component: 'use client'; import React, { useEffect, useState } from 'react'; import { u ...

Update the state in the componentDidMount lifecycle method

Embarking on a project using React to hone my skills, but encountered an error while trying to populate an array with data from a JSON file in the ComponentDidMount() hook. It seems this issue stemmed from a previous error: cannot read property 0 of undef ...

Implementing a timed delay before assigning a class in the state

I am trying to implement a delay before applying for a new class. This is my current situation const [isDone, setIsDone] = useState<boolean>(false); Within a method, I have the following code snippet const myMethod = () => { .... .... se ...

Encountering issues with @typescript-eslint/typescript-estree due to using a non-officially supported version of TypeScript after updating Nuxt

After upgrading Nuxt in my project using the command npx nuxi upgrade, I encountered an issue while running eslint .. The output displayed a warning regarding the TypeScript version: ============= WARNING: You are currently running a version of TypeScript ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

Troubleshooting Clarifai object error while invoking "model.predict" within Angular Framework

I've been attempting to utilize Clarifai's color API to extract the different colors present in an image. Unfortunately, I am encountering challenges when trying to call the API, as it consistently returns empty objects. Below is the snippet of ...

Access denied for generating login hint on target domain in javascript web application for Google sign-in

Utilizing the Google signin Javascript API with the gapi-signin-button on a webapp. The app is being served by a gulp server, binding to 0.0.0.0. Everything works fine during local development, but encountering issues when accessing the page through a publ ...

Structuring a TypeScript microservices repository on GitHub: Best practices to follow

Currently, I am in the process of designing a set of microservices. The structure I have been following involves each item having its own repository. my-project-logger my-project-numbers-service includes: my-project-logger type definitions + class obje ...

Is there a way to dynamically fetch and run JavaScript code from the server without resorting to the use of the

In my current project, I am developing a unique PHP framework that empowers PHP developers to effortlessly craft ExtJS interfaces containing forms, grids, tabpanels, and menus exclusively through PHP classes. To illustrate, creating a TabPanel in this fra ...

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

Verify whether the object is properly implementing the interface

Design: export interface Person { id: number; firstName: string; lastName: string; age: number; } Is there a way to verify that an object returned from the backend aligns with the structure defined in the Person interface? ...

Minimize the quantity of data points displayed along the X-axis in a highcharts graph

After making an API call, I received data for a Highcharts graph consisting of an array of datetimes (in milliseconds) and corresponding values (yAxis). The data is fetched every 15 minutes and displayed on a mobile device. When viewing the data monthly, ...

Using jest.fn() to simulate fetch calls in React

Can anyone explain why I have to include fetch mock logic within my test in order for it to function properly? Let's take a look at a simple example: Component that uses fetch inside useEffect and updates state after receiving a response: // Test.js ...

Tips for generating a unique user validation hash or token

I have a registration endpoint in my express app where users need to verify their email before account activation. I'm struggling with creating a hash for the verification link. I considered using JWT, but it feels like an overcomplicated solution. Is ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

Looking for an API to retrieve random quotes and images from a website?

Greetings, my name is Antika. I recently embarked on a coding journey and have been focusing on learning HTML/CSS along with the basics of JS. Level of Expertise: Beginner During my exploration, I stumbled upon this intriguing website - . It stands out a ...

Nodemailer is experiencing difficulties when used within the routes directory

Recently, I encountered an issue with my subscribe form. It functions perfectly when called from app.js where the express server is defined. However, when I move subscribe.js to the routes folder and connect both files, it fails to send emails. Upon pressi ...