JavaScript API Response - conditional statement for handling a 'null' response

Does anyone have any suggestions for the following scenario:

I have a response in .json format containing personal data of a person, who may or may not be assigned to a project.

Here is an example response where the person is not assigned to a project:

"contactPerson": {
      "id": "someUUID",
      "firstName": "string",
      "lastName": "string",
      "email": "string",
      "title": "string"
    },
    "project": null

And here is an example response where the person is assigned to a project:

"contactPerson": {
      "id": "someUUID",
      "firstName": "string",
      "lastName": "string",
      "email": "string",
      "title": "string"
    },
    "project": {
      "id": "projectUUID",
      "name": "This is a project name ",
      "fullName": "This is a full project name with over 55 chars",
}

I've tried using a simple if statement, but it hasn't been successful.

if (typeOf(response.body[i].project.id !== null) {
 //assert elements in project array
} else {
//assert is 'null
}

However, I keep getting the following error:

Cannot read properties of null (reading 'id')

Does anyone have a solution on how to resolve this issue? I need to assert whether a project is assigned or not.

Thank you in advance

Answer №1

It's important to note that response.body[i].project.id will not have a defined value because response.body[i].project is actually null.

This situation will result in an error being thrown;

TypeError: Cannot read properties of null (reading 'id')

As noted in the comments, simply verifying the existence of response.body[i].project is sufficient.

Using typeof on response.body[i].project will indicate that it is indeed an object.

In order to handle this scenario effectively, you can:

if(response.body[i].project)

This approach works because null is considered a falsy value, so it is equivalent to:

if(response.body[i].project == null)

To explicitly check for null:

if(Object.is(response.body[i].project, null))

Or

if(response.body[i].project === null)

const response = {
  "contactPerson": {
      "id": "someUUID",
      "firstName": "string",
      "lastName": "string",
      "email": "string",
      "title": "string"
    },
    "project": null
};

console.log(response.project); // null

console.log(typeof(response.project)); // object

console.log(response.project == null); // true

console.log(response.project === null); // true

console.log(Object.is(response.project, null)); // true

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

Preventing Repetition in an HTML List using JavaScript

My HTML list is populated with values from JSON, and I have a button on the page. <button onclick="printJsonList()">CLICK</button> This button triggers the following JavaScript function: function printJsonList(){ console.log(ctNameKeep); ...

Using jQuery to update a specific item in a list

My current project involves developing an Image Gallery app. It uses <img> tags within li elements. The code snippet is as follows: var $slideR_wrap = $(".slideRoller_wrapper"); var $slidesRoller = $slideR_wrap.find(".slidesRoller"); var $slideR ...

CSS: Hover below the designated target to reveal an expanding dropdown menu

My initial solution involved toggling the visibility on and off when hovering. However, this approach is not optimal as the menu should smoothly transition into view. When the visibility is toggled, the user does not experience the intended transition effe ...

Enhance the Error class in Typescript

I have been attempting to create a custom error using my "CustomError" class to be displayed in the console instead of the generic "Error", without any success: class CustomError extends Error { constructor(message: string) { super(`Lorem "${me ...

Tips for using the Enter key to shift focus to the next input field

I am trying to move to the next input field when I hit the enter key. I found a solution in another question here, but the code provided doesn't work for me because my input fields are inside a table. Here is my HTML code: <form action="#"> < ...

Hide the div element when the url contains the word 'word'

I did some research online, but I couldn't find any information on whether this is doable. I'm currently using IPBoard and after their latest IPS4 update, I'm facing an issue where I can't simply change the homepage anymore. Now, I have ...

JQuery HTML form validation continues to send emails even when there are blank entries

I've set up an HTML form with three required fields, and I'm trying to prevent the form from submitting an AJAX call if those fields are left empty. $("#contact").submit(function(e){ e.preventDefault(); var ajaxurl = '<?php echo ...

Numerous Google Gauges featuring varying sets of options

Currently, I am facing a challenge involving the insertion of multiple instances of Google Gauges (or Highchart Gauges) on a single page. The goal is to utilize different option sets and separate their placement accordingly. Unfortunately, the solution pro ...

Steps to include a title next to a progress bar:

Is there a way to achieve something like this? I attempted to use bootstrap but I ran into an issue where the title was slightly misaligned below the progress bar. Can someone offer assistance with this matter? Apologies if this has been asked before. H ...

Establishing a recurring interval when the component mounts for a specified period of time

I have read through several Q&As on this topic, but I am still unable to pinpoint what mistake I am making. The code snippet below is meant to display a countdown in the console and update the DOM accordingly, however, it only prints 0s in the console ...

The Rails base file contains a function, let's call it function A, which calls another function, function C. However, function C is defined in two separate JavaScript files

My project includes an application_base.js file with a function: function drawLocations(canvas, blag, blah) { //do some stuff selectLocations(a_something, b_something); //do some stuff } For Page 1: page_1.js function selectLocations(a_somet ...

Is there a way for me to invoke a different function that is located external to

I am currently in the process of setting up an event that triggers on any change within the form input class. import React, { useState } from "react"; DealerRegistration extends React.Component { state = { business_type : 'd ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...

Updating data in Redux triggers a refresh of Material UI table data

Utilizing the material-ui data table component to showcase data, enabling users to update and save information via a form when clicking on a row. Implemented react-redux for state management and dispatching updated rows to the existing data. However, despi ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

Learn how to create a web application by utilizing HTML5 and REST, and then seamlessly transfer the front-end code to a mobile app using Cordova

Can a mobile application be developed from a web portal using Cordova or similar frameworks? The web portal will consist of: HTML5 for front-end J2EE for back-end with JAX-RS Is it feasible to extract pages from the web portal and integrate them into a ...

Using jQuery AJAX to Populate a Textbox and Dropdown Menu

I am new to using JQuery AJAX, so I am still learning the syntax. Currently, I am retrieving values from a database and populating a dropdown box. What I would like AJAX to do is fill in three other fields with hardcoded information when a selection is mad ...

When a function is called, retrieve a specific number of elements from an array using the slice method in

If I have an array of 15 objects, but I am only displaying 5 on the browser using this code: const displayedArray = array.slice(0,4) I also have a function that will load another 5 objects each time a user scrolls down. displayedArray.concat(array.slice ...