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

Hidden overflow and identification in URL causes content to be invisible and suddenly appear at the top of the page

I'm encountering a strange issue with containers that have overflow:hidden and when the page URL includes an id. The content gets pushed up and becomes invisible. This problem arises when I apply padding and negative margin at the bottom to create equ ...

What is a more effective method for linking values with variables in an object?

Can you suggest a more efficient way to write this in JavaScript? let foo; if(bar) { foo = bar.value; } I am attempting to prevent a react error from occurring when `bar` is null if I were to use const foo = bar.value. ...

Is it possible to invoke a helper function by passing a string as its name in JavaScript?

I'm encountering a certain issue. Here is what I am attempting: Is it possible to accomplish this: var action = 'toUpperCase()'; 'abcd'.action; //output ===> ABCD The user can input either uppercase or lowercase function ...

Surprising outcomes when using Mongoose

Questioning Unusual Behavior There is a model in question: //test.js var mongoose = require('../utils/mongoose'); var schema1 = new mongoose.Schema({ name: String }) var schema2 = new mongoose.Schema({ objectsArray: [schema1] }); schema1.pre( ...

Adjust the size of the canvas element based on changes to its parent's dimensions

I am working with an application that includes a div containing a canvas element to display an image. Additionally, there is a sidebar that can be hidden with the click of a button, causing all other elements to resize and adjust to the remaining space. W ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

What is the best way to fetch values from individual buttons using PHP?

<form action="posts-ayarlar.php" method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left"> <table class="table table-striped table-bordered" ...

When the state inspection fails due to a missing object property, the function will not work as intended

I'm currently in the process of developing a weather app. The user will input either a zip code or a city name + state, triggering the $.getJSON function to gather data. One key feature I am working on involves checking if the user's input is va ...

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

The browser is unable to load the local JSON file due to an XMLHttpRequest error

I have been attempting to import a json file into a table, after conducting thorough research I finally discovered some solutions on how to achieve this. However, when trying to implement it in Chrome, I encountered the following error: XMLHttpRequest ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

Encountered an unexpected token '{' error in Discord.js and Node.js integration

let user = message.mentions.users.first(); if (message.mentions.users.size < 1) return message.reply('Please mention someone to issue ARs.').catch(console.error); mcash[${user.id}, ${message.guild.id}].mc ...

Innovative manipulation of arrays using Javascript

Let's say I have some sample input data: data = [ { color : 'Red', number : 5}, { color : 'Blue', number : 3 }, { color : 'Green', age : 8 }, { color : 'Red', number : 7 } ] and I am looking to combine ...

Javascript recursive method for fetching data entries

Seeking a solution to retrieve interconnected records based on a parent column, where the relation can be one or many on both ends. After attempting a recursive function without success, I found my code became overly complex and ineffective. Is there a st ...

Having trouble connecting the HTML file with the JavaScript file

This is my unique HTML file <!DOCTYPE html> <html> <head> <script src="ll.js"></script> </head> <body> <link rel="stylesheet" href="home.css"> ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

How do I save the value of a callback function in Vue data?

#I am facing an issue where the value of this.zuobiao is not being logged after I call the function that assigns a value to it. Why is this happening? getUserProfile() { uni.getLocation({ type: 'gcj02 ', geocode: true, success: (res) => ...

Incorporate seamless integration by using the npm install command

I am currently facing an issue where I need to identify and remove unused dependencies from my package.json file every time I run npm install for my app. Is there a method to automatically include the npm package https://www.npmjs.com/package during the n ...

When deploying a Node.js Express API using Docker, the headers are not being sent

After creating a Node.js Express API, I implemented the /login endpoint for users to authenticate and receive an Authorization Token: @Post('/login') @UseBefore(validationMiddleware(LoginUserDto, 'body')) async logIn(@Res() res: R ...

Display a specific paragraph inside a div using jQuery

I am having trouble getting my jQuery code to display a specific paragraph when a particular div is clicked on. My goal is for the content "v" to be displayed if the user clicks on the ".Virus" div, and for the contents of ".screenInfo" to be shown if the ...