Delete the final comma in a JSON file using JavaScript so that it can be utilized by a Vue application

Using Axios in my Vue app, I am consuming a JSON file. The field "country" contains trailing commas which are creating issues.

Here is the structure of the JSON:

 "country": "spain,france,"  
        ....
    "country": "spain,belgium,"
    ...

In my JavaScript code, I successfully replaced 'france' with 'XXXXXX', as shown below:

const arr = this.countries;
            const newArr = arr.map((countries) => {
             if (countries === "france") {
               return "XXXXXX";
             }
          //   return countries;
             });
           console.log("commas " + newArr); 

I have tried different approaches to remove the trailing commas without success. Can someone offer assistance on how to achieve this?

Answer №1

Upon reaching this juncture, where the XML provides the "country" value stored in a variable like countryString, you can implement the following steps:

let countryString = "germany,italy,";

let countries = countryString.split(",").filter(item => item).map((item) => {
    if (item === "italy") { return "YYYYYY"; }
    return item;
});
console.log(countries);

Answer №2

If you want to eliminate the last character from a string in JavaScript, you can use the slice method like this:

let countryString = "belgium,france,";
countryString = countryString.slice(0, -1); 
console.log(countryString)

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

What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used Object.assign({}, xyz) and other times they used Object.assign([], abc); Could there be a distinction between the two methods? ...

Determine the height of an element in JavaScript or jQuery by using the CSS property height: 0;

I'm facing a challenge in determining the actual height of an element, which currently has a CSS height property set to: height: 0; When I check the console, it shows a height of 0, but I'm looking to find the real height of the element. I als ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Ways to incorporate a smooth transition between the opened and closed fab functionality

I am currently utilizing VueJS and Vuetify in my project. I have successfully implemented Vuetify's FAB component, which displays a list of fab buttons as demonstrated in the documentation: <div id="fab-button"> <v-speed-dial v-mo ...

Exploring the dynamic duo of Django and DataTables: a guide on incorporating

Have you cautiously attempted to fetch data using AJAX, and displaying it in a datatable works seamlessly, but the issue arises when attempting to search or sort within the table. It seems that upon doing so, the data is lost, necessitating a page reload. ...

JavaScript Issue Causing Jquery Carousel Dysfunction

I am having trouble with the slider I created using JS Fiddle. The link to the slider is not working and I need some assistance. Click here for the slider <div class="row"> <div id="myCarousel" class="carousel slide vertical"> &l ...

Personalized typeface for stencil.js element

I am currently working on a stencil component and I need to specify a font for it. Here is what I have so far: index.html <body> <sidebar-component webpagename="dashboard"></sidebar-component> </body> <style> * { m ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

Issue: Reactjs - Material-UI HTML Tooltip does not display dynamic HTML content.In the Reactjs

I have been using a customized HTML MUI Tooltip. Currently, it is functioning with static content but I am looking to make it dynamic. Unfortunately, it is not working with dynamic HTML content. Here is my attempted approach: const ADJUSTMENT_HELP_TEXT = ...

Eslint for Typescript in Vue is throwing an error with a message "Unexpected token, expecting ','. Make sure to

Whenever I attempted to utilize vue's type assertion, I kept encountering this eslint error. To illustrate, consider the following snippet: data: function () { return { sellerIdToListings: {} as any, // 'as' Unexpected to ...

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

What is the best way to calculate the total number of results using ajax?

Encountering an issue with the total count of ajax search results. Getting an error message "Method Illuminate\Database\Eloquent\Collection::total does not exist." when using directives, for example: <div class="searched-item"&g ...

Generate an HTML document from a website page

Having difficulty grasping this concept. I am completely lost on where to begin. It is imperative that I determine how my website can generate a file (whether it be HTML or Text format) and enable users to download it, similar to the functionality in Goo ...

Can content be dynamically loaded through ajax in Simile Timeline instead of being loaded upfront?

I am currently utilizing the JavaScript Simile Timeline which includes timeline items with extensive description fields. Rather than including all this information in the initial JSON payload data, I only want to load it when a user clicks on a timeline it ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Display a collection of Mongoose objects in a React component

In my development stack, I rely on node js + React. The data I work with comes from mongoose and typically follows this format: { "_id": "61b711721ad6657fd07ed8ae", "url": "/esports/match/natus-vincere-vs-team-liquid- ...

Upgrade your input button style using jQuery to swap background images

I have an input button with an initial background image. When a certain condition changes, I want to update its image using jQuery without overriding the button's global CSS in the stylesheet. Is there a way to only change the background attribute wit ...

Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter: <p>dummy paragraph</p> <test></test> <!-- vue component ...