2017-07-26 73 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(",");