Inspecting a collection of elements

To verify if each array length of objects in

inspectionScheduleUnitContactArtifactDto
is equal to 0, return true if there is at least one object with a length of 0. Otherwise, return false if all lengths are greater than 0 or if there are no objects with a length of 0.

#example object

{
    "id": 218,
    "propertyId": 22977,
    "inspectionScheduleUnitArtifactDto": [
        {
            "id": 524,
            "inspectionScheduleUnitContactArtifactDto": [
                {
                    "id": 1097,
                    "inspectionScheduleUnitArtifactId": 524,
                    "primaryContactName": "fsdfsdf"
                }
            ]
        },
        {
            "id": 525,
            "inspectionScheduleUnitContactArtifactDto": [
                {
                    "id": 1100,
                    "inspectionScheduleUnitArtifactId": 525,
                    "primaryContactName": "Name"

                },
                {
                    "id": 1101,
                    "inspectionScheduleUnitArtifactId": 525,
                    "primaryContactName": "342423432"
                }
            ]
        },
        {
            "inspectionScheduleUnitContactArtifactDto": []
        }
    ]
}

Answer №1

To simplify your question, we can rephrase it as follows: If there is at least one object in the

inspectionScheduleUnitContactArtifactDto
array that is empty, return true; otherwise, return false. The most straightforward way to achieve this is by using the some method, which will immediately return true once the condition is met without iterating through the entire array. If the condition is not met after checking each element in the array, then it will return false.

In order to streamline work with your object structure, I utilized the following interfaces:

export interface InspectionSchedule {
  id: number,
  propertyId: number,
  inspectionScheduleUnitArtifactDto: InspectionScheduleUnitArtifactDto[]
}

export interface InspectionScheduleUnitArtifactDto {
  id: number,
  inspectionScheduleUnitContactArtifactDto: InspectionScheduleUnitContactArtifactDto[]
}

export interface InspectionScheduleUnitContactArtifactDto {
  id: number,
  inspectionScheduleUnitArtifactId: number,
  primaryContactName: string
}

By importing these interfaces, you can implement the function below:

containsZeroLengthArray(inspectionSchedule: InspectionSchedule) {
  return inspectionSchedule.inspectionScheduleUnitArtifactDto
    .some(contact => !contact.inspectionScheduleUnitContactArtifactDto.length);
}

Note: The expression !someArray.length evaluates to true when the array is empty.

Answer №2

Assuming familiarity with the object layout and relevant classes containing data, I've crafted sample classes resembling the data presented:

export class A {
    constructor(id: number,
    inspectionScheduleUnitArtifactId: number,
    primaryContactName: string) { }
}

export class B {
    constructor(id: number | null, 
    inspectionScheduleUnitContactArtifactDto: A[]) { }
}

export class C {
    constructor(id: number, propertyId: number, 
    inspectionScheduleUnitArtifactDto: B[]) { }
}

To determine if any inner array is empty, you can utilize filtering based on array length as shown below:

// Mock data setup
const a1: A = new A(1097, 524, 'fsdfsdf');
const a2: A = new A(1100, 525, 'Name');
const a3: A = new A(1101, 525, '342423432');
const b1: B = new B(524, [a1]);
const b2: B = new B(525, [a2, a3]);
const b3: B = new B(null, []);
const c: C = new C(218, 22977, [b1, b2, b3]);

// Check for any empty inner arrays in inspectionScheduleUnitContactArtifactDtos
const anyEmpty: boolean = c.inspectionScheduleUnitArtifactDto
    .filter(x => x.inspectionScheduleUnitContactArtifactDto.length === 0)
    .length > 0;

Answer №3

If you need to check for the existence of an empty property with a specific name within nested objects, consider using a recursive function:

var dataObj = {
    "id": 218,
    "propertyId": 22977,
    "details": [
        {
            "id": 524,
            "contacts": [
                {
                    "id": 1097,
                    "name": "John Doe",
                }
            ],
        },
        {
            "id": 525,
            "contacts": [
                {
                    "id": 1100,
                    "name": "Jane Smith",
                },
                {
                    "id": 1101,
                    "name": "Bob Johnson",
                }
            ],
        },
        {
            "contacts": [],
        }
    ]
}

function checkEmptyProperty(obj, propertyName) {
    for (const key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        
        if (obj[key] instanceof Array || obj[key] instanceof Object) {
            if (key === propertyName) {
                if (obj[key].length > 0) {
                    if (checkEmptyProperty(obj[key], propertyName)) return true;
                } else {
                    return true;
                }
            } else {
                if (checkEmptyProperty(obj[key], propertyName)) return true;
            }
        } else {
            if (key === propertyName) return true;          
        }
    }
    
    return false;
}

// This will output 'true' as there are empty contact arrays
console.log(checkEmptyProperty(dataObj, 'contacts'));

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

How can I close a dialog within an iframe in jQuery?

Suppose I initiate a dialog in this way: $('<iframe id="externalSite" class="externalSite" src="http://www.example.com" />').dialog({ autoOpen: true, width: 800, height: 500, modal: true, resizable: ...

What is the best way to provide data to a directive if the scope is asynchronously populated?

Within my code, I have a controller responsible for fetching data asynchronously. This data is then used by a directive in the application. Unfortunately, there seems to be an issue with the directive not displaying the fetched data properly. Interestingl ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...

a beginner's guide to utilizing the grunt target

Here is an example of my Gruntfile.js: 'use strict'; module.exports = function(grunt) { grunt.initConfig({ grunt.config.set('targ', grunt.option('target')); cachebuster: { build: { ...

Contrasting document and $document in AngularJS

What sets apart the usage of document from $document in Angular application development? I have come across recommendations to opt for Angular's counterparts like: $window over window or $timeout instead of setTimeout. But... why is this advised? I i ...

Center-aligned Circles via CSS with the number of circles controlled by AngularJS

Here is what the layout looks like: https://i.sstatic.net/Cz0CT.png Here is what I would like to have: https://i.sstatic.net/WbkY2.png Or if the getNumber function returns more, for example: https://i.sstatic.net/ViBXh.png (so essentially the circles ...

Join the community of Angular enthusiasts by subscribing to Angular2

Is there a way to create a separate method in the service to save data and call that method to retrieve it for multiple components in my project? The first method retrieves reusable data, while the second method is supposed to return the data. However, it ...

Can one retrieve a value using the append/html function?

Here is some HTML code: <div id="price-tag"><i class="fa fa-inr"></i> <span id="price"></span></strong></div> We have a JavaScript function that appends a value to the span element: $("#price").html(Price); Now ...

Struggling to insert a JavaScript variable into a MySQL database table using PHP and AJAX

As a newcomer to these technologies, I've been struggling all day with what I expected to be a simple task. My goal is to pass a parameter from a JS function to my PHP code using AJAX and then insert that parameter into my database. Here's the J ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

Customizing the color scheme of specific components using Material UI inline styling

I am currently customizing my TextFields from Material-UI. My background is black and I want both the textField border and text to be white. Here's the relevant part of my code: render() { const styles = { width: { width: '90%& ...

"If the local field matches a field in a foreign document, aggregation will be enabled

I am currently working with MeteorJS and using the meteor call method to fetch data successfully. I have also implemented the $lookup for aggregation, which is functioning well. However, my goal now is to retrieve only unique data and avoid duplicates. [! ...

There was an issue attempting to create an instance of a class within another class

I'm attempting to access a class called "Skills" and use it within another class named "Employee" to assign skills to employees. However, I am encountering an error that says Uncaught ReferenceError: Skill is not defined at Employee.js:21, and I can&a ...

What is the best way to perform an AJAX request on Hackerrank using JavaScript?

As I dove into the Hackerrank example test, I experimented with various methods for making an AJAX call. XMLHttpReq, fetch, and others were attempted but none seemed to work; both XHR and fetch methods were unavailable. My first attempt was with fetch: as ...

unable to disable custom field component in Angular Material

I've built a unique slide toggle feature using Angular Material. The steps I followed to create it can be found here: https://material.angular.io/guide/creating-a-custom-form-field-control While everything works smoothly, there's an issue when I ...

How can I alter an object within an array of a document using a query in Mongoose?

I am working with a data structure: { field: 1, field: 3, field: [ { _id: xxx , subfield: 1 }, { _id: xxx , subfield: 1 }, ] } My task is to update a specific element within the array. Currently, my method involves removing the old obj ...

Revamping Modal Interface for CRUD Operations (React / C# / Entity Framework Core)

After successfully implementing Create, Read, and Delete operations in my project using C# and Entity Framework Core, I encountered a roadblock while trying to update data. Despite updating the data as expected, I keep facing an issue at the .CommitAsync() ...

Best practices for logging error objects in JavaScript

As a beginner in web development, I've recently come across an interesting observation related to handling errors. When working with json.stringyfy(), I noticed that the message key is not displayed in statement 2. However, accessing error.message ret ...

Sorting through a list of strings by checking for a specific character within each string

After spending years dabbling in VBA, I am now delving into Typescript. I currently have an array of binary strings Each string represents a binary number My goal is to filter the array and extract all strings that contain '1' at position X I ...

Angular ng-select displaying the "&" symbol as "&amp;"

I am encountering a situation where the selected option is displaying with "&" instead of just "&" character. Is there a way to display the string value as is without interpreting it as HTML code, while also ensuring there are no security vulnerabilit ...