typescript 如果value为空,如何从字符串中删除逗号?

ktca8awb  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(183)

在O/P中,如果属性是空的,我会在字符串的中间和结尾看到, ,,因为它们是用逗号分隔的。我怎样才能删除它,应该只有一个逗号,即使键是空的?
Exp O/P:授权再分销商(AR)、文档· L1、合规性· 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);
mzillmmw

mzillmmw1#

1.在map()之前使用filter()来过滤掉selectedObj.checked
1.使用filter()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);

相关问题