如何将管道分隔的字符串拆分为对象数组

我有管道分隔的字符串(sshshhs , 1) | (ee23es , 1),我想分割并创建一个对象数组。结果一定是这样的[ {name:sshshhs,value:1},{name:ee23es,value:2} ]。我是 JavaScript 新手,有人可以帮助我吗?



天涯尽头无女友
浏览 121回答 2
2回答

有只小跳蛙

查看此代码片段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 };})通过这种方式,使用一个正则表达式就可以摆脱管道和括号。然后使用映射从每个元素中提取名称和值。

犯罪嫌疑人X

您有多种方法可以将您转变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帮助您创建自己的解决方案
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript