2 回答

TA貢獻1824條經驗 獲得超8個贊
查看此代碼片段
let myString = "(sshshhs , 1) | (ee23es , 1)";
// extract only the elements
let stringList = myString .split(/\) \| \(|\(|\)/);
// remove first and last empty elements, due to regex
stringList = stringList.slice(1,-1);
//split each element into an object
let objList = stringList.map(s => {
const [name, value] = s.split(',').map(el => el.trim());
return { name, value };
})
通過這種方式,使用一個正則表達式就可以擺脫管道和括號。然后使用映射從每個元素中提取名稱和值。

TA貢獻2080條經驗 獲得超4個贊
您有多種方法可以將您轉變string為arrayobject
其中之一可能是split多次并用于reduce使object
"(sshshhs , 1) | (ee23es , 1)"
.split('|') // here we first split with the principal key
.map(e => {
return [e.replace(/\(|\)/g, '')] // we create an object of your values to reduce it
.reduce((result, token) => {
const [name, value] = token.split(',').map(e => e.trim()); // we get the key/values by splitting it (and trimming it by the same time)
return {name, value}; // we then return the finded name and value
}, {})
})
這絕對不是最有效的方法,但它將幫助您了解背后的機制split并reduce幫助您創建自己的解決方案
添加回答
舉報