When the array object is undefined, it does not appear in the DIV

I am retrieving JSON data containing an array and using it to create an unordered list. The issue arises when some of the entries do not have the values for "artistName" and "trackName", leading to them being displayed as Undefined. How can I modify the code below to only display entries that contain values for both "artistName" and "trackName"?

let output="<ul>";

for (let i in data.onNow.playlist) {
    if (data.onNow.playlist[i].hasOwnProperty("artistName") && data.onNow.playlist[i].hasOwnProperty("trackName")) {
        output+="<li>"+data.onNow.playlist[i].artistName+
            " - "+data.onNow.playlist[i].trackName+"</li>";
    }
}

output+="</ul>";

document.getElementById("playlist-container").innerHTML=output;

Answer №1

let myList = "<ul>";

for (let index in data.currentPlaylist) {
    let currentSong = data.currentPlaylist[index];

    if (currentSong.artist && currentSong.track) {
        myList += "<li>" + currentSong.artist + " - " +
            currentSong.track + "</li>";
    }
}

myList += "</ul>";

This method helps in excluding tracks and artists with empty names.

if (bar) will return false for bar values like false, null, undefined, the number 0, an empty string, or NaN. All other values will result in 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

Guide on using AngularJS UI Router module for filtering JSON data based on a particular object property

I've got a collection of emails stored in a JSON file, each with its own properties: {"id":5,"lu":false,"statut":2,"nom_expediteur":"Brian Patterson","nom_destinataire":"Frank Martin","email_expediteur":"<a href="/cdn-cgi/l/email-protection" class ...

The method .replace() is used to substitute instances within a string

I have set up input fields for users to enter tags. For example, if a user enters "xyz_DTL_D, John_D" it will be stored in the tagArr[] array. My goal is to replace the input "_D" with an empty string. So I created the following code: var dailycheck = ...

"Step-by-step guide on duplicating a document in MongoDB Collection with the help of Mongoose and Node.js

Is it possible to duplicate a document to the same or a new collection with a new _id? Below is the data retrieved from the query stored in "doc" (res.query) [ { _id: new ObjectId("614d4766fb2600340fdb2904"), templateName: 'first template&a ...

Verify if the element is positioned at the top of the screen using the Selenium JavaScript web driver

Currently utilizing the Selenium web driver from this link to test a website. My goal is to determine if my view is positioned at the top of the entire screen. I have tried using both isDisplay() and getLocationInView, but they only provide absolute posit ...

Move the divs within the overflow container by sliding them, then take out the initial element and append it to the end

Currently, when I utilize .appendTo(".wrapper") as shown in the code below, it eliminates the animation effect. My goal is to have the div on the far left slide out of view, triggering an overflow hidden effect, and then be placed at the end of the slide c ...

What is the most effective way to implement a single modal throughout my web application without having to duplicate HTML code on each page?

After realizing I was repetitively adding the same div to every page for a modal dialog, I decided to place a single div in the site.master page and call it when needed. This method worked fine until I began implementing ajax with partial page updates. H ...

A guide on integrating with the ShiftPlanning.com API using ColdFusion's CFHTTP

The ShiftPlanning API documentation for authentication () specifies a POST request in JSON format for authentication: { "key": "YOUR_API_KEY", "request": { "module": "staff.login", "method": "GET", "username": "xxxxxxx", "password": "x ...

How can you use JavaScript to iterate through an Array of Objects and create a new Object that combines arrays based on a specific key?

How can JavaScript iterate through an Array of Objects and return a new Object with merged arrays based on Object keys? The original Array of Objects is as follows: this.obj = [ { "name": "test name 1", "teams": [{ "manage ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

Saving the output of mySQL queries on the client side for later use in subsequent requests

While logging a user in, I transfer attributes through a response object. In the javascript, I store specific attributes to a variable for future usage. For example, onresponse - currentUser = req.body.user currentID = req.body.id etc. Later, if I need t ...

Is there a way to transfer PHP user information (session) to a Node.js server?

Currently, I have two separate pages set up for my website. One is the Chat page, which operates on Node.js and Socket.io using WebSockets. The other is the main page where users login and access various features. I am looking to implement a system where, ...

Populating an array prior to AJAX transmission

I'm not a JavaScript expert, particularly when it comes to promises and callbacks. However, my goal is to have my JavaScript file perform the following tasks synchronously: 1. Create an array 2. Populate the array with all the necessary elements 3. Se ...

The issue of ajax data not being sent during an update in jQuery sortable has been identified

Having an issue with a piece of javascript/jQuery code that utilizes the sortable function of jQuery. I am using it to arrange divs whose number is unknown, and currently attempting to send this data to the database through ajax: Using Javascript with jQu ...

Encountering a parse error while sending an AJAX JSON request to a PHP file

In my PHP file, I have code that reads data from a geoJSON file, extracts necessary information and sorts it into an associative array. To retrieve this sorted data through AJAX, I make a call to the PHP file. However, I encounter an error saying "SyntaxEr ...

Changing a string into an ArrayList of Strings using Java

There is a string that looks like this - "["222.222.222.222", "21.21.21.21"]"; // A plain string that represents a JSON array I need to extract 222.222.222.222 and 21.21.21.21 from the string and store them in an ArrayList. Your help would be greatly ap ...

Show values in array that include a certain keyword

Currently, I am developing a search function for my json decoded results The code snippet that I have written is as follows: <?php foreach($soeg_decoded as $key => $val){ $value = $val["Value"]; $seotitle = $val["SEOTitle"]; $text = $va ...

Tips for including multiple directives in a component

Apologies in advance for my lack of clarity in expressing this question, which is why I am seeking assistance rather than finding the solution on my own. My query pertains to loading a component within another one and specifying it in the directive. Below ...

Is it possible for an Ajax/jQuery script to display multiple dependent dropdown box options within a single Form URL?

In the process of developing a basic form prototype that includes 4 entries in PythonAnywhere (Python 3.7 + Django): PinID (Independent, simple manual number entry) Region (Independent Dropdown Box) Name (Region-Dependent Dropdown Box) Source (Name-Depen ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...

Combining Arrays of Javascript Objects with Different Data Types

I have two arrays of objects which I need to combine in a specific way. You can view the arrays here: https://plnkr.co/edit/RQs9WWs1hcxmuKGIgEhM?p=preview My goal is to merge these arrays so that any elements missing from one array are added to create a c ...