簡體   English   中英

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

[英]How to split pipe separated string into array of object

我有管道分隔的字符串(sshshhs , 1) | (ee23es , 1) (sshshhs , 1) | (ee23es , 1) ,我想拆分並制作一個 object 數組。 結果必須類似於[ {name:sshshhs,value:1},{name:ee23es,value:2} ] 我是 JavaScript 的新手,有人可以幫助我。

謝謝

看看這個代碼片段

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

通過這種方式,您可以使用一個正則表達式擺脫管道和括號。 然后使用地圖從每個元素中提取名稱和值。

您有多種方法可以將string轉換為object array

其中之一可能是多次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
    }, {})
})

這絕對不是最有效的方法,但它會幫助您理解splitreduce背后的機制,並幫助您創建自己的解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM