Function for verifying presence of empty nested elements (comprising of Arrays, Sets, Strings, and Maps)

I am currently exploring ways to develop a solution using plain JS (without relying on any external libraries) that can determine whether a given input is considered 'empty' or not.

Below are the code snippets and test cases I have prepared for this purpose, with expected outcomes specified as comments alongside each test case.

Despite my efforts in creating functions to thoroughly validate these assertions on stackblitz, I have yet to achieve complete coverage.

https://stackblitz.com/edit/node-ksxnjm

const assert = require('assert');



function isEmpty(obj) {
  return Object.keys(obj).every((k) => !Object.keys(obj[k]).length);
}

const test1 = {};                  // expect true
const test2 = { some: 'value' };   // expect false
const test3 = { some: {} };        // expect true
const test4 = [];                  // expect true
const test5 = [[]];                // expect true
const test6 = { some: [] };        // expect true
const test7 = { some: ['barry'] }; // expect false
const test8 = { some: new Map() }; // expect true
const test9 = {
  response: new Map([['body', new Map([['something', {}]])]]),
};                                 // expect true
const test10 = {
  response: '{"body":{"something":{}}}',
};                                 // expect true

const test11 = {
  something: { somethingElse: {} },
};                                 // expect true

assert.strictEqual(isEmpty(test1), true);
assert.strictEqual(isEmpty(test2), false);
assert.strictEqual(isEmpty(test3), true);
assert.strictEqual(isEmpty(test4), true);
assert.strictEqual(isEmpty(test5), true);
assert.strictEqual(isEmpty(test6), true);
assert.strictEqual(isEmpty(test7), false);
assert.strictEqual(isEmpty(test8), true);
assert.strictEqual(isEmpty(test9), true);
assert.strictEqual(isEmpty(test10), true);
assert.strictEqual(isEmpty(test11), true);

While my current function adequately handles most of the provided test cases, it falls short when dealing with nested objects and stringified objects. I find myself at an impasse on how to address this issue.

What approach should I take to accommodate these specific scenarios?

EDIT:

const test12 = {
  something: {
    somethingElse: {
      number: 1,
      someSet: new Set(['garry']),
    },
  },
}; // should evaluate to false

const test13 = new Map([
    ['something', new Map([
        ['somethingElse', new Map([
            ['number', 1],
            ['someSet', new Set(['garry'])]
        ])]
    ])]
]); // should also evaluate to false

Answer №1

To determine if a value is empty, you can utilize a recursive function structured as follows:

  • Begin by verifying if the passed value is an object
  • If the object contains a values function, fetch the values using Array.from(o.values()) (This works for Set, Map, and Array objects)
  • Recursively invoke the isEmpty function on each value
  • If the input value is a string, validate if it is truthy (You may customize this part accordingly)
function isEmpty(o) {
  if (typeof o === "object") {
    let values = typeof o.values === "function"
                  ? Array.from(o.values())
                  : Object.values(o)
    
    return values.every(isEmpty)
  } else {
    var parsed = parseJsonString(o)
    return parsed ? isEmpty(parsed) : !o
  }
};

function parseJsonString(str) {
    try {
        return typeof str === 'string' && JSON.parse(str);
    } catch (e) {
        return '';
    }
}

Here's a snippet that you can run to test the function:

...
(additional code snippets for testing purposes)
...

Answer №2

In order to tackle this challenge effectively, I believe utilizing Recursion is the best approach.

Firstly, it's crucial to determine the type of data you are currently dealing with and then check if there is any content within it. If there is, you will need to recursively call the isEmpty function to examine the inner data type and content.

const isEmpty = value  =>{
  if(typeof value === 'object'){
    if(Object.keys(value).length === 0) return true
    for (const property in value) {
     isEmpty(property)
    }
    
    
  }
  else if(typeof value === 'string'){
    //check for string 
  }
  //...
  //...
  //...
  //other data types
}

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

Discover the steps to update the information displayed on a tab through $stateProvider

I'm working on a view that has the following structure: <h2>Data Package Management</h2> <div class="row push-down-md"> <tabs data="tabData" type="tabs"></tabs> <div class="col-md-12"> <tabset&g ...

Tips for clearing an observable in Angular version 4

In the code snippet below, an observable has been created: private permissionSubject = new Subject<any>(); permissionObservable$ = this.permissionSubject.asObservable(); constructor( public apiService: ApiService) { } updatePermissionsDat ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

Tips for modifying the color of a query term in HTML

Within my HTML file, I have <p class = "result"> {{searchResult}} </p> where {{searchResult}} represents the result of a search term. If I search for the term "hot", {{searchResult}} would display a string containing the word "hot" in a ...

Retrieving a JSON string by looping through an array nested inside an object

I am currently developing an application that involves parsing a JSON file to extract strings from it. However, I am facing difficulty in retrieving one specific string into my activity. The string in question is located within Object > Array > Strin ...

Searching for specific items within an array of objects using Mongoose

Currently, I am working with a Mongoose schema that looks like this: var MessageSchema = new Schema({ streamer: { streamer_username: String, streams: [{ id: String, messages: [{ date: String, ...

The tooltip content is a little too narrow

I have successfully implemented QTip2 to display a tooltip: The content of the tooltip is generated in the following method: public string GetHours() { DateTime d = Convert.ToDateTime(Request.Form["date"]); Bump b = new Bump(); ...

Discover the complete guide on incorporating a JavaScript library with additional dependencies in Angular 2

I am a beginner with angular 2 and I am attempting to integrate the Miso Dataset JavaScript library into my angular 2 project. The Miso library requires other JavaScript libraries as dependencies. Although I have included all the necessary JavaScript file ...

Bootbox Dialog Form

Looking to implement a functionality where a Bootbox dialog pops up with an "OK" button. Upon clicking the "OK" button, it should initiate a POST request, sending back the ID of the message to acknowledge that the user has read it. The Bootbox dialog fun ...

Executing a JavaScript function without passing arguments does not yield the desired result

Within my JS file, I encountered an issue when trying to call one function from another. Initially, I called the function with no arguments using only its name handleResponse. However, when attempting to add arguments by changing the function signature, I ...

Merging data between two JsonBuilder objects

Looking to merge data from one JsonBuilder object into another JsonBuilder object is the goal here. Here's my current approach: public String buildOneUser(DyveUserDTO user) { def userBuilder = new JsonBuilder() userBuilder user.collect { ...

Guide on designing a navigation list with unique buttons that alter the displayed content based on the selected button

As a newcomer to the world of programming, I have a basic inquiry that I hope you can assist me with. I have successfully created a navigation list, but I am struggling to make it functional. For instance, if my navlist consists of 3 buttons: Home, About, ...

Tips for adding a placeholder in a login form on Drupal 7

Can anyone help me set a placeholder for a horizontal login form in Drupal 7? I want the placeholder text to disappear when clicked on, and I want it to display 'username' and 'password'. Here is the current code for the form. Thank you ...

Guide to changing the background color of material ui drawer component using styled-components

Issue with Styling Material Ui Drawer Using Styled Components In my application, I am utilizing a Material ui drawer in conjunction with Styled components. Although I have successfully styled several simple Material ui components using Styled components a ...

Using jQuery to target the td:nth-child selector inside a document.ready function is not viable

Currently, I am working on a language learning project where I import a table of German words and their English translations from a .csv file using the jQuery.csvToTable plugin. My goal is to replace the words in the cells with an HTML input when the lang ...

Searching for a file using Powershell in one directory and replacing it with a different file in another directory based on

I'm new to exploring the world of PowerShell, and I've recently been tasked with creating a script for the infrastructure team. Essentially, I have a text file containing a list of file names. These files are located in two separate areas, which ...

HTML script tag without a specified type

Exploring asp.net and frontend technologies for the first time. The code snippet I'm working with is as follows: <ul> @foreach (var item in Model) { <li> <img src="@item" alt="file here" width="100" height=" ...

Improve the organization of my JavaScript code

This code snippet is specifically designed for a shoe website, where it automatically adds the shoe in the desired size to your cart as soon as the page loads. The "skuAndSize" variable represents the shoe size used by the website. In this case, a selecte ...

I've been attempting to develop a React application, but I consistently encounter the following error: "npm ERR! cb() function was never invoked!"

Here is the issue at hand: HP@DESKTOP-1HP83V8 MINGW64 ~/Desktop/Web-Development (master) $ npx create-react-app my-app A new React app is being created in C:\Users\HP\Desktop\Web-Development\my-app. Packages are being installed. ...

Trouble with linking an external JavaScript file in HTML document

I'm having some trouble including an external JavaScript file in my HTML. I followed the steps but the pie chart is not showing up as expected. Can someone please take a look and let me know if I missed anything? Here's the link to where I got th ...