How to ignore db empty fields to use .charAt(0)?!

Hi
I want to define the options of a drop-down list using 3 fields of a database:
firstName
middleName,
lastName
Examlpe: John P. Henderson (John Peter Henderson).

This post by Jeff helped me a lot. But, since not all people have the middle name, I have trouble using “.charAt(0)”
Here is the result without .charAt(0):

How could I ignore the middleName just for items without middleName?
page link: https://www.douglasgrppractice.com/Appointment/Form/Getting_Started

If I use .charAt(0) as below, the drop-list wont work.
$w.onReady( function () {
wixData.query(“TherapistsDB”)
.limit(1000)
.find()
.then(results => {
const lists = getLists(results.items);
$w(“#therapistList”).options = buildOptions(lists);
});
function getLists(items) {
// Use the map method to create the titlesOnly object containing all the titles from the query results
const nameList = items.map(item => item.firstName + ’ '+ item.middleName .charAt(0) + ’ ’ + item.lastName);
return nameList;
}
// Creates an array of objects in the form {label: “label”, value: “value”} from the array of titles
function buildOptions(a) {
return a.map(tt => {
// Use the map method to build the options list in the format {label:uniqueTitle, value:uniqueTitle}
return {label:tt, value:tt};
});
}
});

Thanks in advance,
Ali

So add a condition:

 let nameList;
if(item.middleName){
   nameList = items.map(item => item.firstName + ' '+ item.middleName.charAt(0) + ' ' + item.lastName); 
} else {
 nameList = items.map(item => item.firstName +  ' ' + item.lastName); 
}

[updated so it’ll be in the global scope]

Thank you J.D.
I couldn’t use your code in the global scope, out of the function. It gave me errors.

I got this when I paste it inside the function:


If I change the item to items .middleName, the middle name won’t show up.


Here is my live db:

it should be item s .middleName not item.middleName, but even that won’t work.
Let’s do it differently, use your original code but change this line - instead of:

 const nameList = items.map(item => item.firstName + ' '+ item.middleName.charAt(0) + ' ' + item.lastName); 

do:

let nameList = [];
items.forEach((item) => {
    let initial = " ";
    if(item.middleName){initial += item.middleName[0] + " ";}
    nameList.push(item.firstName + initial + item.lastName);
})

Thanks a LOT J.D.
You did it.
I really appreciate your help


here is my code just in case:

Cheers…