esLint throws an error advising that a for-in loop should be enclosed within an if statement in order to exclude unnecessary properties from the prototype

While working on my Angular project, I encountered an error with esLint related to the code snippet below:

private calculateFieldValue(value: any): any {
                let isEmptyObject = false;
                if (value && Array.isArray(value) && value.length === 1 && value[0]) {
                    for (const subAttr in value[0]) {
                        if (value[0].hasOwnProperty(subAttr)) {
                            if (value[0][subAttr]) {
                                break;
                            }
                        }
                        isEmptyObject = true;
                    }
                }
                return isEmptyObject ? null : value;
            }

The specific error that occurred is:

Error: The body of a for-in loop should be wrapped in an if statement to filter unwanted properties from the prototype chain. (guard-for-in)

Answer №1

Despite having a check for hasOwnProperty, it does not encompass the entirety of the loop body; isEmptyObject = true; will still run even if value[0] lacks that property. The linter requires you to execute statements in the body only if hasOwnProperty is successful.

for (const subAttr in value[0]) {
    if (value[0].hasOwnProperty(subAttr)) {
        if (value[0][subAttr]) {
            break;
        }
        isEmptyObject = true;
    }
}

I strongly advise against using any as it undermines TypeScript's purpose by essentially disabling various types of type-checking. Since you are returning either the array or null, utilize generics to specify the type of the array instead of resorting to any.

An alternative approach would be to employ Object.values to determine if any values are truthy - your focus is solely on the values, not the keys.

function getSubarrayObjectWithTruthyProperty<T extends unknown>(value: Array<T> | unknown) {
    if (value && Array.isArray(value) && value.length === 1) {
        const item: unknown = value[0];
        if (item && typeof item === 'object' && Object.values(item).some(Boolean)) {
            return value as T;
        }
    }
    return null;
}

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

After downloading the quickstart (angularjs2) from angular.io, I encountered an error when trying to start npm

[email protected] typing start G:\quickstart\quickstart-master tsc && concurrently "tsc -w" "lite-server" [1] 'lite-server' is not recognized as a valid command, [1] executable program or batch file. [1] lite-serve ...

Uploading videos on Mobile Safari causes the website to refresh automatically

Setting up a photo uploading server on a raspberry pi using Angular with Node.Js and multer has been an exciting project for me. I opted to host it on an unsecured ad-hoc network created by the pi itself so I can easily take it on road trips and store phot ...

specifying a specific type in a declaration

In this scenario, my goal is to distinguish between different types when declaring a new type: type Schedule = { flag_active : boolean, } type Channel = { flag_archived : boolean } type CreateChangeLog = { from : null, to : Schedule | Channel } ty ...

AngularMap with mapping as the value

Can I implement a Map<string, Map<string, number>> collection in my Angular project? I attempted to create and initialize the variable, but encountered an error when trying to set values. Here is an example: //define variable public players: M ...

What's causing the "* before initialization" error in Vue with TypeScript?

I am encountering an issue with my code where I get the error "Cannot access 'AuthCallback' before initialization" when attempting to call the router function in the AuthCallback component. What could be causing this problem? The desired function ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

`How to utilize the spread operator in Angular 4 to push an object to a specific length`

One issue I'm facing is trying to push an object onto a specific index position in an array, but it's getting pushed to the end of the array instead. this.tradingPartner = new TradingPartnerModel(); this.tradingPartners = [...this.tradingPartner ...

Rows in angular ag grid are vanishing when data is filtered

My ag grid includes custom components for each column, but I'm facing an issue where the components disappear when filtering the data. For example: the component inside the row To apply filtering, I use an input with a filtering function: <data-gr ...

Building a .NET Core 3.1 application that integrates SQL Server 2019 Express for managing multiple databases, including a main database dedicated to

I'm currently developing a web application using .NET Core 3.1 and Angular 9. I am curious to know if it is feasible to leverage the internal authentication/authorization system in .NET Core to connect to an "authorization" database. This would allow ...

Angular 2 eliminates the need for nesting subscriptions

Is there a way to streamline nested subscriptions like the code snippet below? I want to extract values from the subscription for better organization, but using a global variable won't work because the subscription hasn't received the value yet. ...

Setting a data type for information retrieved from an Angular HTTP request - A Step-by-Step Guide

Here is the code I use to fetch data: login() { const url = api + 'login'; this.http.post(url, this.userModel) .subscribe( data => { localStorage.token = data.token; this.router.navigate(['/home&a ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

What is the correct way to use forwardRef in a dynamic import in Next.js?

I've been trying to incorporate the forwardRef in my code, but I'm facing some difficulties. Can anyone help me out with this? I'm encountering the following errors: Property 'forwardedRef' does not exist on type '{}'. ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

What is the best way to invoke a function in a specific child component from its parent component?

It seems that I might have provided too much information, but the main question remains: how can I call a method in the child component from the parent template's click() event. <button(click)='get()'>GET</button> In my case, th ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

Is there a way to customize the active width of ngx-tooltip specifically for an edge or link?

For my project, I am trying to incorporate a ngx-tooltip on the connection between two nodes. The tooltip is functioning well for both nodes and edges, but the edge size is smaller, requiring precise mouse positioning to trigger the tooltip. <ng-temp ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

[attr.disabled]="isChecked ? '' : 'disabled'"

[attr.disabled]="isChecked == true ? '' : disabled" Can anyone assist me with disabling unchecked checkboxes in a loop using Angular 8? [attr.disabled]="isChecked == true ? '' : disabled". Need help with this in Ang ...

Strange behavior observed in Angular Reactive form

I've been troubleshooting this code snippet: login.component.html <div class="main"> <div class="image"> <img src="./assets/icons/login.png" alt="Login"> <p>Sign in t ...