繁体   English   中英

我如何检查对象的typeSoftware是否具有(-1)值并将其从中删除?

[英]How can i check if the Object' typeSoftware has (-1) value and remove it from it?

我有这个对象,类型软件是他的财产,在某些情况下我为-1。 我想先将其从对象中删除,然后再去服务器

对象companyName:“ dsfdsfdsfsd” companyVatId:“ dsfdsfdsf” companyWebsite:“ dfdsfsdf”国家/地区:“ DZ”电子邮件:“ sdfsdfs@gmail.com” firstName:“ sdfsdf” lastName:“ fsdfs”其他:“ dsfsdfs”电话:“ sdfsdfs” positionInTheCompany:“ dfsdfsd”产品描述:“ dsfsdfsdf”产品名称:“ sdfdsfdsf”类型软件:“ 2,-1”

结果应该是这种情况:

对象companyName:“ dsfdsfdsfsd” companyVatId:“ dsfdsfdsf” companyWebsite:“ dfdsfsdf”国家/地区:“ DZ”电子邮件:“ sdfsdfs@gmail.com” firstName:“ sdfsdf” lastName:“ fsdfs”其他:“ dsfsdfs”电话:“ sdfsdfs” positionInTheCompany:“ dfsdfsd”产品描述:“ dsfsdfsdf”产品名称:“ sdfdsfdsf”类型软件:“ 2”

您可以使用正则表达式或数组函数来实现。 如果对象是字符串,则必须首先调用JSON.parse(o)

 //o is your Object o = {typeSoftware: '2 , -1 ,6'} o.typeSoftware = o.typeSoftware.split(',').map(x => x.trim()).filter(y => y !== '-1').join(', '); console.log(o.typeSoftware) 

此正则表达式将帮助您删除字符串中的最后一个-1, -1

'2, -1'.replace(/(,|^)\s*-1$/, '')

这里是一个例子:

 const typeSoftware = '-1'; const result = typeSoftware.replace(/(,|^)\\s?-1$/, ''); console.log(typeSoftware); console.log(result); 

您可以使用替换捕获组

\btypeSoftware:\s*"([^"]+)"

通过这种模式,我们捕获了typeSoftware: " followed by value "

在replace函数的回调中,我们获取捕获的组并将其拆分,然后过滤掉所需的值并加入它们,

 let str = `Object companyName: "dsfdsfdsfsd" companyVatId: "dsfdsfdsf" companyWebsite: "dfdsfsdf" country: "DZ" email: "sdfsdfs@gmail.com" firstName: "sdfsdf" lastName: "fsdfs" other: "dsfsdf" phone: "sdfsdfsdfsf" positionInTheCompany: "dfsdfsd" productDescription: "dsfsdfsdf" productName: "sdfdsfdsf" typeSoftware: "2, -1" ` let final = (str) =>str.replace(/\\btypeSoftware:\\s*"([^"]+)"/g, (match,g1)=>{ return `typeSoftware:"${g1.split(',').filter(e=> e.trim() !== '-1' && e).join(',')}"` }) console.log(final(str)) // this will handle following case too console.log(final(`typeSoftware:"-1, 2, 5, 9"`)) console.log(final(`typeSoftware:"2, -1, 4,"`)) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM