What is the best way to eliminate a comma from a string if there is no value present?

When the properties are empty in the output, I notice a double comma (,,) in the middle and at the end of the string due to being separated by commas. How can I remove this so that there is only a single comma even when keys are empty?

Expected Output: Authorized Redistributor (AR), Document · L1, Compliance · L1

const arr = [{
    "id": "324101",
    "role": "Authorized Redistributor (AR)",
    "license": "Target",
    "dataConcept": "Agreement · L1, Asset · L1, Account · L1",
    "managedGeography": "International · L2",
    "managedSegment": "Core Citi Businesses [L2]",
    "enterpriseProduct": "Borrowing Products · L2"
  },
  {
    "id": "324230",
    "role": "Authorized Redistributor (AR)",
    "license": "",
    "dataConcept": "Document · L1, Compliance · L1",
    "managedGeography": "",
    "managedSegment": "",
    "enterpriseProduct": "",
    "checked": true,
    "checkBoxPatched": true
  }
]

const adsList = arr.map(selectedObj => {
  if (selectedObj.checked) {
    return selectedObj.role + ", " + selectedObj.license + ", " + selectedObj.dataConcept + ", " + selectedObj.managedGeography + ", " + selectedObj.managedSegment
  } else {
    return '';
  }
}).filter((str) => str.length !== 0).join(';\n\n');

console.log(adsList);

Answer №1

  1. Prior to using map(), apply filter() to exclude objects with selectedObj.checked
  2. To remove empty values, utilize both filter() and join()

const arr = [{id:"324101",role:"Authorized Redistributor (AR)",license:"Target",dataConcept:"Agreement \xb7 L1, Asset \xb7 L1, Account \xb7 L1",managedGeography:"International \xb7 L2",managedSegment:"Core Citi Businesses [L2]",enterpriseProduct:"Borrowing Products \xb7 L2"},{id:"324230",role:"Authorized Redistributor (AR)",license:"",dataConcept:"Document \xb7 L1, Compliance \xb7 L1",managedGeography:"",managedSegment:"",enterpriseProduct:"",checked:!0,checkBoxPatched:!0},{id:"324383",role:"System Of Record (SOR)",license:"Target",dataConcept:"Market \xb7 L1, Holding \xb7 L1",managedGeography:"",managedSegment:"",enterpriseProduct:""},{id:"324410",role:"System Of Record (SOR)",license:"Interim",dataConcept:"Holding \xb7 L1, Party \xb7 L1, Balance \xb7 L1, Account \xb7 L1, Compliance \xb7 L1",managedGeography:"",managedSegment:"Corporate / Other [L2]",enterpriseProduct:"Borrowing Products \xb7 L2, Fee-Based Products \xb7 L2, Lending Products \xb7 L2, Issued Monetary Instruments \xb7 L2, Traded Loans \xb7 L2, Deposit Products \xb7 L2, Treasury Management \xb7 L2"},{id:"364769",role:"System Of Record (SOR)",license:"Interim",dataConcept:"Asset \xb7 L1, Account \xb7 L1",managedGeography:"Total Citi Geography \xb7 L1",managedSegment:"Total Citi [L1]",enterpriseProduct:""}];

const adsList = arr.filter(selectedObj => selectedObj.checked).map(selectedObj => {
  return [selectedObj.role, selectedObj.license, selectedObj.dataConcept, selectedObj.managedGeography, selectedObj.managedSegment].filter(s => s.trim()).join(', ')
}).join(';\n\n');

console.log(adsList);

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

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

Utilizing JQuery's printThis Plugin in Combination with the Style Attribute

I am currently working on a JavaScript app and I am trying to implement a button that will allow users to print a specific div. To achieve this, I am utilizing a jQuery plugin called printThis (github link) as well as attempting to use window.print(). $(" ...

Using localStorage in an Angular template: a comprehensive guide

Currently, I am facing some issues with localStorage on a website as I am unable to get a * ngif directive to function as desired. To provide further context: When a user logs in, their information is stored in the localStorage under the 'identity&ap ...

Tips for extracting only key-value pairs with true values from an array of objects

I am working with an array of objects obtained from an API. The data received has multiple values, but I am interested in displaying only the access that a user has. For example, if a user only has read access, I want to display the read key. ...

Creating an HTML5 canvas that expands to cover the entire html document

After learning JavaScript, I decided to create a page on Github. Everything seems fine, except that the JS code for canvas doesn't scale to fit the entire HTML page. The particles only bounce off the initial window, leaving empty space when scrolling ...

Use Javascript to search for phone data within the object and showcase it in a table

When a key is pressed in an input field, JavaScript retrieves data from a JSON object and displays it in an HTML table. I require assistance with: 1: Sort the data by phone number and only display the table row that contains numbers from the input, hid ...

Encountering unresolved JSX elements while utilizing input field

import React from 'react'; class AjaxIO extends React.Component { constructor(props) { super(props); this.state = { count: "1" } } render() { return ( <div> {this.state.count} </div> ...

Enhance Your NestJS Application by Extending Mongoose Schemas and Overriding Parent Properties

In order to achieve the desired functionality, I have a requirement for my Class B to extend a Class A. This initial step works as intended; however, the next task at hand is overriding a property of Class A within Class B. More specifically, it is necess ...

Showing the elements of a python list in a dropdown menu on a webpage using AJAX

I'm currently utilizing Django and AJAX to create a chained dropdown feature. The user will initially choose a brand_name from a dropdown menu, and based on that selection, the names of all products made by that brand will be populated in a second dro ...

The functionality of react-router-dom's NavLink isActive feature seems to be unreliable

We are currently immersed in a React.js project. I am in the process of setting up multiple pages using react-router-dom and my goal is to alter the active icon by using NavLink. The icon+sel signifies the active page. render() { const oddEvent = (mat ...

Clickable label for checkbox in Android browser is unresponsive

I've been experimenting with creating a responsive CSS menu using the checkbox hack Here's the HTML: <input type="checkbox" id="button" /> <label for="button" onclick>click / touch</label> <div> Change my color! </d ...

Toggling with Bootstrap 5

I implemented the toggler button using bootstrap 5 in the navbar, but I am facing an issue where the navbar items are not displayed when the browser screen is minimized. What could be causing this problem? And how can I fix it? <!DOCTYPE html> < ...

Possible conflict between CSS and JavaScript on Magento website

Problem Description: Visit this link for more details I am facing an issue with the product upload process when using certain attributes. It appears to be related to a positioning problem. Despite trying various solutions, such as removing the position at ...

jQuery can be used to access and read the `$_FILES['name']['tmp_name']` data

I am working on an application to import Excel files into a database using excel_reader2.php. I have set up a form for uploading the Excel file, and once the desired file is selected, I need to read the data from the worksheet of the Excel file. However, I ...

What is the best way to open multiple tabs simultaneously on Google Chrome?

I'm in the process of developing a coupon product and I want to be able to open 4 tabs with just one click of a button. Interestingly, this works smoothly on Firefox, however, when it comes to Chrome, only 2 links are able to open while the other two ...

When an if-statement is not executing within the useEffect hook but successfully runs outside of it in NextJs/JavaScript

Trying to shift my if-statement [line 30] located in useFetchMovieGenreResults [inside the hooks folder] from outside my useEffect to inside it seems to be causing issues. Instead of getting the expected output (an object), I encounter an error message. I ...

Having trouble loading the JSON data for display

My select dropdown is supposed to display the names of states. The data is being fetched from PHP and is also available in the controller JS file. However, the data is showing up as blank in the HTML. When I use console.log(), the fetched result from PHP s ...

Creating sequential hover animations with CSS in HTML

I have a total of four divs that I want to hover continuously, one after the other. Here is the code I am currently using: #rij1 .content-overlayz, #rij1 .content-details { animation-duration: 2s; animation-name: stepped-pulse; animation-iterati ...

Display the closing tag depending on specific conditions to simulate the behavior of a calendar

Is it possible to conditionally render a closing tag using v-if? If so, what is the correct way to do it? Initially, I tried the following: <template v-for="day in days"> <td class="days">{{day.number}}</td> <template v-if ...