为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

天涯尽头无女友 2023-07-06 14:49:35
我有管道分隔的字符串(sshshhs , 1) | (ee23es , 1),我想分割并创建一个对象数组。结果一定是这样的[ {name:sshshhs,value:1},{name:ee23es,value:2} ]。我是 JavaScript 新手,有人可以帮助我吗?
查看完整描述

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 };

})

通过这种方式,使用一个正则表达式就可以摆脱管道和括号。然后使用映射从每个元素中提取名称和值。


查看完整回答
反对 回复 2023-07-06
?
犯罪嫌疑人X

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帮助您创建自己的解决方案


查看完整回答
反对 回复 2023-07-06
  • 2 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号