Split a pipe delimited key-value pair separated by '=' symbol

后端 未结 6 1225
醉梦人生
醉梦人生 2020-12-29 08:46

We are receiving an input parameter value as a pipe-delimited key-value pair, separated with = symbols. For example:

\"|User=0101|Name=ImNewUse         


        
6条回答
  •  遥遥无期
    2020-12-29 09:10

    Without mutation

    You don't need the outer pipes. If necessary, trim them off str.slice(1, str.length - 1)

    const str = "User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235";
    
    str.split('|').reduce((accum, x) => { 
      const kv = x.split('=');
      return {...accum, ...{[kv[0]]: kv[1]}};
    }, {})
    

提交回复
热议问题