Check if a certain object is devoid of any values based on the elements in an array - JavaScript

I have collected data related to various businesses:

{
    "business": {
        "type": [
            "LLC",
            "Corporation"
        ],
        "LLC": {
            "status": "active",
            "profits": 1000000,
            "period": "yearly"
        },
        "corporation": {},
        "partnership": {}
    }
}

I am seeking advice on how to validate the "corporation" object. I want to ensure that if the "type" array includes the string "Corporation", then the "corporation" object must not be empty.

Although I attempted using validate.js to check for emptiness, it does not allow me to specifically target the strings within the type array for validation.

const validate = require('validate.js');
if (validate.isEmpty(business.LLC)) {
    return wrapper.error('fail', 'Object is empty');
}

Your assistance on this matter would be greatly appreciated 🙏🏻

Answer №1

I finally solved it and didn't even realize my mistake, big thanks to dinesh for the help!

The key is to first check the array, then proceed to examine the objects below.

if (payload.business.type.includes('Corporation')) {
      if (validate.isEmpty(payload.business.corporation)) {
        return wrapper.error('fail', 'Object is empty');
      }
    }

Answer №2

let data = {
    "company": {
        "category": [
            "Tech",
            "Finance"
        ],
        "Tech": {
            "status": "active",
            "revenue": 5000000,
            "period": "quarterly"
        },
        "finance": {},
        "healthcare": {}
    }
}

Utilize includes method to verify the elements within array,

data.company.category.includes("Finance")

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

Warning for pending changes prior to moving in Svelte

My current setup involves a Svelte application that includes form content. Whenever a modification is made within the form, an "unsaved change" alert can be triggered upon page refresh. However, when attempting to navigate to a different page using Svelt ...

Node.js and MongoDB integration for implementing like and dislike buttons

I have been struggling to create a system for liking and disliking posts in my project. The issue I am facing is with the communication between the server and client side. Here is the form I am using: https://i.sstatic.net/IBRAL.png When I click on the li ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

Outer div encapsulating inner div within its boundaries

I am looking for a solution where the inner div stays fully contained within the outer div, without overflowing and overlapping with the padding of the outer div. Here is a code sample that demonstrates the issue .inner { /* Overflow */ overflow-wra ...

Use a for loop to fill an array with values and then showcase its contents

I have been trying to figure out how to populate an array and display it immediately when targeting the route in my NodeJS project. Currently, I am able to console log a list of objects. However, I want to populate an array and show it when accessing loca ...

Enhancing AngularJS view rendering using ngshow

Currently, I am working on a view where ng-show is used to display a select DOM object when certain conditions are met, and an input DOM for all other scenarios. However, I have noticed that there is a significant delay in the disappearance of the input bo ...

Initiate the Material TextField onChange event from within a nested component

I am currently working on a component that looks like this: class IncrementField extends Component { inputRef; changeValue() { this.inputRef.value = parseInt(this.inputRef.value) + 1; } render() { const { ...other } = this.props; return ( ...

Binding attributes in knockoutjs following an AJAX request

The objective Incorporate the attr binding of KnockoutJS following an AJAX call. The dilemma Check out the code snippet below: $.ajax({ url: "/Products/List?Output=JSON", dataType: "json", success: function (data) { $.each(data, fun ...

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on ...

Styling Challenges with CSS/AngularJS Accordion in Footer

I want to create a page layout as shown below: +---------------------------+ | Auto-fill / v scrollable ^| | || | || | v| +---------------------------+ | Fixed [][][] ...

Combining mouse interactions with animated bar transitions

I want to create a graph with dynamic bar height transitions whenever it is drawn or redrawn. Once the bars are displayed, I would like mouse events (mouseenter, mouseleave, and mousemove) to trigger a tooltip showing information about the specific bar bei ...

What is the best way to display a Vuex state based on a function being activated?

I have noticed similar questions on this topic but couldn't find a solution, so I decided to create my own. Here's the issue: I have an array named "allCountries" in the state, initially filled with 250 country objects. I am successfully render ...

The scrolling behavior of Chrome tabs or bookmarks can impact the functionality of an Angular

I recently came across a strange problem with my angularjs page that includes a slick carrousel. In the controller, I have code that listens for the $destroy event to remove certain injected elements by slick. However, I noticed that whenever I scroll ov ...

How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my ...

Make the child div images disappear gradually and at the same time, make an overlapping parent div image appear using Javascript

Check out my attempt at solving this challenge on jsfiddle: http://jsfiddle.net/oca3L32h/ In the scenario, there are 3 divs within a main div. Each of these divs contains an image and they overlap each other. By using radio buttons, the visibility of the ...

There was a TypeError encountered in a Node application, stating: "Unable to access the 'trim' property of an undefined

Currently, I am developing a JavaScript application that follows the MVC model. In the controllers, there is a userController.js file, and in the models, there is a user.js file which contains a cleanup function. However, I am encountering a TypeError: Can ...

Sending data to another page by selecting a list item

Being new to web programming and JavaScript, I am facing a scenario where I have a list of requests displayed on one page and I need to pass the ID of the selected request to another page to display all the details of that particular request. I am strugg ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

Is jQuery .ajax not able to make CORS request while Native XMLHttpRequest() successfully does?

When I use the vanilla XMLHttpRequest() object to make a CORS request, it works perfectly fine. However, when I try using the jQuery.get() function, it tells me that cross-origin requests are not allowed. This is confusing because $.get() is built on top o ...