Utilizing Regular Expressions to Substitute 'null' in API Data with a Custom String in JavaScript

I'm working with an API to gather information about books, including the title and author. However, I've noticed that some authors' data is returned as 'undefined'. I had the idea of using regular expressions (RegExp) to replace this undefined value with 'N/A', but I am encountering difficulties implementing it.

/* within a function */
function fetchingAsyncData() {

  /* data fetching process */

  const responseData = await response.json();

  const foundBooks = [];

  for (let i = 0; i < responseData.items.length; i++) {
    let bookTitle = responseData.items[i].title;
    let bookAuthor = responseData.items[i].author;

    if (typeof bookTitle === 'undefined' || typeof bookAuthor === 'undefined') {

      // Attempting to replace 'undefined' with 'N/A'

    }

    foundBooks.push(`${responseData.items[i].title} by ${responseData.items[i].authors}`);
  }

  return foundBooks;
}

An example of the current output: ["Cats by undefined"], however I am aiming for the desired result: ["Cats by N/A"].

Answer №1

There is no need to use a regular expression in this situation, as undefined is not a string but a special type. The best approach is to simply replace the value with a default option; a common method is to use short-circuiting:

let titles = data.items[i].title || 'N/A';
let authors = data.items[i].author || 'N/A';

This technique works because the || ("or") operator chooses the first non-falsy value from the list, or the last one if they are all falsy. Since undefined is considered falsy and strings are truthy, this code snippet will assign the existing string value if it is present, or 'N/A' if it is undefined.

Answer №2

This method presents a unique approach by utilizing a default object to fill in any missing gaps within the objects provided. The main benefit is that it simplifies the process of adding new properties during consolidation, making it more manageable. However, it is important to note that this approach does not leave much room for inherent logic when filling in these gaps.

const def = {author: 'N/A', title: 'N/A'} 
let data = [
  { author: 'A1', title: 'T1'},
  { author: 'A2'},
  { title: 'T2'}
]

data = data.map(x => Object.assign({},def , x))

console.log(data)

Answer №3

If the variable titles is of type string and contains the value "undefined", you can manipulate it using RegEx with following code:

...
titles = titles.replace(/undefined/g, "N/A");
...

However, if titles is actually undefined (has no value), it's recommended to handle it like this:

titles = titles || 'N/A';

This will set titles to "N/A" if it's undefined, null, empty string or 0 (for number type), otherwise it will keep the original value of titles.

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

Leveraging Angular for Parsing JSON Data

I have a JSON object that I want to use in my code. The goal is to assign the values of certain properties from the JSON object to four variables in my Angular project. These variables are named as follows: authorText : string; titleText : string; duratio ...

How many characters are in SCEditor? Let's calculate and display the count

Currently, I am utilizing the real simple WYSIWYG editor SCEditor for my website. I am curious about how I can precisely determine the current number of characters in its textarea and display them below it? Although I posted a question on GitHub, it seem ...

"Angular encountered an error while attempting to access the property 'data' from an undefined

I'm encountering an issue when trying to retrieve data from a JSON file. Upon clicking a button to display the data in a textarea, the first click does not yield any result, but subsequent clicks work as expected. The program functions by fetching an ...

The Jquery .remove() function will only take effect after the second click

I am currently working on implementing a notifications feature using bootstrap popover. The issue I am facing is that after a user clicks on a notification, it should be removed. However, for some reason, it requires two clicks to actually remove the notif ...

How can I implement disabling buttons for specific IDs in React?

I'm currently developing an interactive quiz application with React that features multiple choice questions. I've implemented state management to track and increment the user's score when they select the correct answer option, but there&apos ...

How can I send an ArrayList item in the body of an HTTP request (POST) using Flutter?

I have an ArrayList where I store data from my API List<GetTestFeeMap> responseArray =[]; // Storing API response Next, I add data to my ArrayList ➡ responseArray.add(getTestFeeObj!); Now I am attempting to retrieve each encTestId. However, it ...

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...

Determine in Jquery if all the elements in array 2 are being utilized by array 1

Can anyone help me figure out why my array1 has a different length than array2? I've been searching for hours trying to find the mistake in my code. If it's not related to that, could someone kindly point out where I went wrong? function contr ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

Can Vue recognize array changes using the Spread syntax?

According to Vue documentation: Vue is unable to detect certain changes made to an array, such as: Directly setting an item using the index, for example vm.items[indexOfItem] = newValue Modifying the length of the array, like vm.items.length = newLength ...

Python script to loop over JSON files and ignore empty files

I have a Python script that reads and converts multiple JSON files into CSV format. The majority of the files follow this structure: { "resultSet": { "totalRecords": "2", "agentLogins": [ ...

Is it possible to remove a specific directory from the webpack build configuration in a vue-cli-3 setup?

After spending 3 hours adding the line: exclude: ['./src/assets/sass'] in 20 different places, I am seeking guidance on where it should actually be placed. Below is my current setup for the css-loader (util.js): 'use strict' const path ...

eliminate a mesh from the view following a mouse hover event triggered by a raycaster

            When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using INTERSECTED.material.color.setHex(radioHoverColor); and reset it ...

When using multer to upload a file, the issue of req.files being undefined may

I am currently working on a Node.js Application using Express.js 4 that involves uploading an image. I opted to utilize the multer module for this task, but encountered an issue with accessing the uploaded file via req.files. Below is the relevant portions ...

The issue persists with UIkit modal element remaining in the DOM even after the parent component in Vue.js is destroyed

In my Vue app, I am utilizing the UIKit modal. UIkit.modal(element).show(); // This adds the class uk-open and sets style to display:block UIkit.modal(element).hide(); When I hide the modal, it simply removes the class uk-open and the inline style of dis ...

Problem with transitioning to a different page on Next.js

I am having trouble navigating to a different page in Next.js using the router.push function. The goal is to route to "example.js" by utilizing a variable called ChangePage, which leads to a single div element on that page. However, despite following the ...

What causes $(this) to stop functioning post successful execution?

Here are the code snippets I'm currently working with: $(this).removeClass('page larger').addClass('current'); $(this).siblings().removeClass('current').addClass('page larger'); Interestingly, when I try to pl ...

I am facing an issue with my React/Redux API where it is not logging out correctly and displaying [[

As a beginner in the coding world, I've run into some challenges while working with a React/Redux API. Following along with Bucky Roberts' YouTube tutorial, I decided to replace his static names object with an API that I then integrate into my r ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

Having difficulty accessing `props` in a React JS and Next JS application

Currently, I am developing a React application that utilizes Server Side Rendering. In this project, I am using React Js and Next Js as my primary framework. My goal is to retrieve initial props using the getServerSideProps method by consulting the documen ...