亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將管道分隔的字符串拆分為對象數組

如何將管道分隔的字符串拆分為對象數組

天涯盡頭無女友 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 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號