查看此代码片段let myString = "(sshshhs , 1) | (ee23es , 1)";// extract only the elementslet stringList = myString .split(/\) \| \(|\(|\)/);// remove first and last empty elements, due to regexstringList = 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 };})通过这种方式,使用一个正则表达式就可以摆脱管道和括号。然后使用映射从每个元素中提取名称和值。
您有多种方法可以将您转变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帮助您创建自己的解决方案