Invalid JSON value returned as 'undefined'

Just diving into the world of json!

Encountered a small problem.

I have a feed that returns the string "undefined" if there is no data for commentnotes.

I simply want to get rid of the "undefined" and make it empty instead.

Below is my JavaScript code:

document.getElementById("tooltipwrap0").innerHTML = '<span style="font-size:22px; font-weight:600;">' + data.users[0].member + " " + data.users[0].party + "-" + data.users[0].state + "<br/>" + '<span style="font-size:18px; font-weight:300;">' + (data.users[0].commentnotes || "") + "";

Here is a snippet of my data feed:

var data={
"users": [
    {
        "member": "first name",
        "party": "F",
        "state": "Ala.",


    },

Any assistance would be greatly appreciated, thank you!

Answer №1

To check for existence in a condition, the in operator can be used as shown below:

if ("commentnotes" in data.users[0])
    // append data.users[0].commentnotes to your string

If the value returned by this operation is undefined (which is falsy), you can retrieve it and use an empty string if it doesn't exist:

data.users[0].commentnotes ? data.users[0].commentnotes : ""

This can also be expressed more concisely as:

data.users[0].commentnotes || ""

Remember to enclose this expression in parentheses when using it within string concatenation.

Answer №2

If the value of data.users[0].commentnotes is falsy or undefined, you can use '' to default to an empty string.

Answer №3

Give this a try:

let outputHTML = '<span style="font-size:22px; font-weight:600;">' + userData.people[0].name + " " + userData.people[0].group + "-" + userData.people[0].location + "<br/>" + '<span style="font-size:18px; font-weight:300;">';

if (userData.people[0].notes){
  outputHTML += userData.people[0].notes;
}

document.getElementById("wrapper0").innerHTML = outputHTML; 

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

Should one prioritize learning TypeScript over diving into Angular2?

Should I prioritize learning TypeScript before diving into AngularJS 2? ...

The JQqplot graph is failing to display correctly following an ajaxpost operation

When drawing a chart in two different scenarios, the first scenario is during the onload event and the second one is after the successful completion of an ajax post. The same code is being called in both scenarios. During the onload function, the chart l ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

Ways to access a function variable within an AJAX `done` function

This is the JavaScript function I am working with: $('.editable').change(function () { event.preventDefault(); var el_text = this.lastElementChild; var action = this.action; var method = this.method; var data = $(this).serialize(); ...

Tips for concealing the loader once all pages have been loaded

Within the context of my website development project at , I am utilizing a script for infinite scrolling to consolidate multiple pages into one seamless scrolling experience. I am seeking a solution to hide the loader (the spinning icon) when no additiona ...

What is the process for showcasing specific Firestore items on a webpage?

database I've encountered an intriguing bug in my code that is proving difficult to resolve. The code involves a straightforward setup with React and Firestore, where items are listed on one page and their details are displayed on the next. However, t ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

Filter JSON data in AngularJS ng-repeat by a specific ID

I'm having difficulty getting this to function properly. I've been attempting to filter a JSON file by specific ID and then iterate using ng-repeat. Here's what I have tried: This is the button trigger: <a href="#/compare-details">& ...

The transformation of a Raphael element does not occur as expected when it is passed to a function within a loop

My attempt to rotate an object by a variable number of degrees in order to mimic a dial was unsuccessful. Initially, I tried the following steps: window.onload = function() { var paper = new Raphael(document.getElementById('canvas_container ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Converting a JSON image string (not a URL) into a UIImage to display

After spending an entire day trying to solve this, I am really desperate for an answer. It seems like a simple task - I have a JSON array of images in the form of strings (I believe). These are not URLs, but rather image file names like "GoodLogo.png". Typ ...

default selection in AngularJS select box determined by database ID

Here is the scenario: ... <select ng-model="customer" ng-options="c.name for c in customers"> <option value="">-- choose customer --</option> </select> .... In my controller: $scope.customers = [ {"id":4,"name":"aaaa", ...

The VueJS dynamic grid view

Currently, I am working on a project in VueJS using vue cli 3. I am facing an issue with implementing MasonryJS into my Vue project. The challenge lies in grasping how to integrate this masonry layout into my Vue application. ; (function(window) { // J ...

The output from using json_encode is not in a valid JSON format

When trying to return JSON using the following PHP code, an invalid format is produced: $sql = 'select * from website where websiteID = "'. $websiteID .'"'; $q = mysql_query( $sql ) or die(mysql_error()); $res = json_encode( mysql_fetc ...

I am looking for a string with this particular format in JavaScript

I am working with a JSON string array that looks like this: var dataMaster = [ {"id":1,"name":"John Doe","age":30}, {"id":2,"name":"Jane Smith","age":28} ] If you want to see how I would like to transform this data, please visit the following lin ...

Button that vanishes when clicked, using PHP and HTML

I am in the process of creating an online store and I am seeking to implement a button that directs users to a new page, but then disappears permanently from all pages within the store. Here is the code snippet I have developed so far: <input class="b ...

What is the designated color for highlighting an option in Next.js?

This is my first time working on a Next.js project and I see an unfamiliar option. Which selection should I choose? I plan to use JavaScript for the Next.js project, not TypeScript. Just need to figure out which option is currently selected so I can pro ...

Listen for the load event during an AJAX request without using jQuery's add

I have four HTML files and four corresponding JavaScript files. Each JavaScript file is externally loaded by its respective HTML file. Specifically, index.html loads javascript.js, 1.html loads javascript1.js, 2.html loads javascript2.js, and 3.html loads ...

There was an unexpected error encountered while trying to use Jade

I encountered an error in my jade template: Error: E:\Do\hello_express\node_notes\views\simple.jade:6 4| meta(charset="utf-8") 5| meta(name="viewport",content="width=device-width,initial-scale=1,maximum-scal ...

Google App Engine - Passing server side data to the client side: Tips and Tricks

When working with Google App Engine, there is a specific object or model called "Car" that resides on the server. This "Car" object possesses various properties such as "Model", "Year", and more. The task at hand involves transmitting information of the "C ...