Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below:

{
  "params": {
    "time_to_diagnosis": [
      {
        "field": "date_of_diagnosis",
        "value": ""
      },
      {
        "field": "date_of_symptom_onset",
        "value": "2019-09-01"
      }
    ],
    "time_since_onset": [
      {
        "field": "date_of_symptom_onset",
        "value": "2019-09-01"
      }
    ]
  }
}

This object consists of nested arrays and objects.

Notice how some keys are empty within these arrays.

The objective is to return true if there are no empty keys within the nested objects, otherwise return false.

Here's a JavaScript function I came up with for this purpose:

const isParamsInAjaxParamsEmpty = (paramsForAjaxCall) => {
  for (const key in paramsForAjaxCall) {
    for (const nestedKey in paramsForAjaxCall[key]) {
      const params = paramsForAjaxCall[key];

      if (params[nestedKey] === "") {
        return true;
      }
    }
  }

  return false;
}

I'm aware that utilizing Array.isArray on the nestedKey could be beneficial, but I'm uncertain about how to implement recursion due to the possibility of having multiple arrays.

The object used in the function is referred to as paramsForAjaxCall.

Any suggestions for improvement?

Answer №1

One approach is to map the array and extract the values from each Object. By using the every function, we can determine if all values meet a certain condition, resulting in an array of booleans due to the process of mapping.

If this array includes a false, then the final result will be false.

const data = {
  "params": {
    "time_to_diagnosis": [{
        "field": "date_of_diagnosis",
        "value": "ddd"
      },
      {
        "field": "date_of_symptom_onset",
        "value": "2019-09-01"
      }
    ],
    "time_since_onset": [{
      "field": "date_of_symptom_onset",
      "value": "2019-09-01"
    }]
  }
}

const res = !Object.values(data).map(o => Object.values(o).map(value => value.every(({
  value
}) => value !== ""))).flat().includes(false)


console.log(res)

Answer №2

To determine whether a property exists in an object, you can start by making sure the object is not null or undefined and return false if it is. Then, you can proceed to check for the desired property or loop through all properties.

function checkProperty(object) {
    if (!object || typeof object !== 'object') return false;
    if (object.value) return true;
    return Object.values(object).every(checkProperty);
}

var data = { params: { time_to_diagnosis: [{ field: "date_of_diagnosis", value: "" }, { field: "date_of_symptom_onset", value: "2019-09-01" }], time_since_onset: [{ field: "date_of_symptom_onset", value: "2019-09-01" }] } }

console.log(checkProperty(data));

data.params.time_to_diagnosis[0].value= "foo";
console.log(checkProperty(data));

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

NextJS is throwing an error: The prop `href` in `<Link>` should be a `string` or `object`, but it received `undefined` instead

I've encountered an issue while trying to integrate a header section from a GatsbyJS project into my NextJS project. The error message I'm receiving is: "Error: Failed prop type: The prop href expects a string or object in <Link>, but ...

The key you entered in local storage was not defined and the value associated with

Having an issue with my HTML signup form where the key is showing as undefined (email should be the key) and the value displays as [object Object]. Any help in resolving this problem would be greatly appreciated. Thank you. <!DOCTYPE html> <html& ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Which element from the context menu has been selected?

We specialize in creating browser extensions for Chrome, Firefox, and Safari. Our latest project involves implementing context menus within the extensions that will appear when users right-click on any editable form element. I attempted to incorporate an e ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

Adjusting the position of the parent div by manipulating the bottom property

Is there a way to toggle the bottom property of a div when clicking its child anchor tag? <div class="nav" :class="{ 'full-width': isFullWidth }"> <a class="toggle-button" @click="toggleNav"><i class="fa fa-angle-down">< ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

What is the best way to mix up the middle letters within certain positions of a word?

Here is what I have managed to achieve so far: mounted() { const randomVariants = [...Array(3)].map(() => this.baseWord .split('') .sort(() => 0.5 - Math.random()) .join('') ) const variantsWithoutIniti ...

24-hour countdown tool featuring a visual progress bar

Currently, I am in the process of developing an application aimed at assisting individuals in either forming new habits or breaking old ones. In this application, I am looking to implement a countdown timer that ticks down daily; with the help of this help ...

Utilizing jQuery to fetch the source value of an image when the closest radio button is selected

On my website, I have a collection of divs that display color swatches in thumbnail size images. What I want to achieve is updating the main product image when a user clicks on a radio button by fetching the source value of the image inside the label eleme ...

Completing a Promise without invoking the 'then' method

As I work on developing a small API for the NPM module Poolio, one common dilemma arises regarding error-first callbacks and promises. The challenge lies in how to cater to both types of asynchronous functions while maintaining consistency in APIs and retu ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

Getting information from PHP through AJAX for transmission to a separate PHP script

Hi everyone, I'm facing a bit of a challenge with my project. Here's the situation: I've got a PHP file that interacts with a database and displays the query results. Then, there's an HTML file that uses AJAX to show these results dyna ...

Interactive front end design for decision trees

On the front end, I aim to enable users to influence the outcome of a Decision Tree based on their selections. For my Django-React App, I have adopted the style and tree example from the codeplayer. You can find it here: I am tasked with creating an unor ...

JQuery addClass function not functioning properly when used in conjunction with an AJAX request

I have a website where I've implemented an AJAX pagination system. Additionally, I've included a JQUERY call to add a class to certain list items within my document ready function. $(document).ready(function(){ $(".products ul li:nth-child(3 ...

React Native Flatlist does not deselect onPress

In my app, I have a flat list that allows users to select items by touching a row. When a user touches a row, the item is selected and its id is stored in an array. However, when the user tries to un-select the item by touching it again, the item is not re ...

Having trouble retrieving the .html() content from the <label> element

Check out the code below: $('.size_click').click(function () { $(this).closest('span').toggleClass('active_size'); $('.selected_sizes').append($(this).closest('label').html()); }); There are multiple ...

Troubleshooting a unique CSS bug in jQuery mouseover functionality

Check out this pen: https://codepen.io/anon/pen/eKzEVX?editors=1111 I recently created a Form Select in Laravel: {!! Form::select('status_id', $statuses, $post->status_id, ['class' => 'form-control post-sub-items-label &apo ...

Express.js is still displaying the 'Not Found' message even after deleting the initial code

Despite multiple attempts to resolve what I initially thought was a caching issue by completely removing all code from my server, I am still facing the same problem: The default error handling provided by Express Generator in the app.js file contains the ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...