2017-07-26 75 views
0

我有一个对象的属性值的一个CSV,我需要从它的Javascript正则表达式:清除CSV

var myObj = { a: "", b: "", c: "c", d: "" }; 

var result = Object.values(myObj).join(","); 
console.log("result before: " + result); // result before: ,,c, 

result = result.replace(/(^\,)|(\,$)|\,\,/, ""); 
console.log("result after: " + result); // result after: ,c, 

删除所有空值,你可以看到我的定制“之旅正则表达式(,) “工作不好,错误在哪里?

我需要删除所有 “,,” 和trimEnd(,)+ trimStart(,)

PS。

A)一种解决方案是过滤对象; B)另一种解决方案是修复正则表达式;

+0

所以你想只是'C'在最后?或'{c:“c”}'? – Vineesh

+0

是的,删除所有空值 – Serge

+0

所以你想要的输出对象与非空值的键权利? – Vineesh

回答

2

而不是使用正则表达式的解决方案,联接才定义的元素。

var myObj = { a: "", b: "", c: "c", d: "" }; 

var result = Object.values(myObj).filter(function(o){ 
    return o; 
}).join(","); 
console.log("result before: " + result); 

正则表达式的解决方案

var myObj = { a: "", b: "", c: "c", d: "" }; 

var result = Object.values(myObj).join(","); 
console.log("result before: " + result); // result before: ,,c, 

result = result.replace(/(^\,+)|(\,+$)|(?!\,[^,])(\,|\,\,+)/g, ""); 
console.log("result after: " + result); // result after: c 

它是如何工作

(^\,+)       Match any number of commas in the beginning of the string 
    |(\,+$)      Or any number at the end 
      |(?!\,[^,])(\,|\,\,+) Or a single, or multiple commas that aren't followed by another character 
+0

伟大的解决方案!我不知道是否是正则表达式中的问题:) – Serge

+0

我已经添加了正则表达式解决方案。 –

0

我认为你可以做这只是循环的关键。

var myObj = { a: "", b: "", c: "c", d: "" }; 
 
    Object.keys(myObj).forEach(function(key){ 
 
     myObj[key]?myObj[key]:delete myObj[key]; 
 
    }) 
 
    console.log(myObj);

0

如果我理解了问题,这将是我的解决方案:

const obj = { a: 'a', b: '', c: '', d: 'd' } 
 

 
const res = Object.keys(obj) 
 
    .reduce((c, e) => obj[e] ? [...c, obj[e]] : c, []) 
 
    .join(',') 
 

 
console.log(res)

0

你为什么不只是过滤您的阵列中的第2行?

var result = Object.values(myObj).filter(function (x) {return x!="";}).join(",");