将一些字符串值转换为数组格式

问题描述 投票:0回答:1

有人可以帮我带来测试值吗:

   let test = "a:1|b:2,3|c:4,5"

转换成以下格式:

   prod:[
         {
           name:test,
           product:{
                     a:[1],
                     b:[2,3],
                     c:[4,5]
                    }
          }]
javascript
1个回答
0
投票

一种解决方案可能如下所示:

const string = "a:1|b:2,3|c:4,5";
const regex = /(\w):([\d,]+)/gm;
const matches = string.matchAll(regex);
const prod = [];
const product = {};

for (const [_, key, value] of matches) {
  const numbers = value.split(",").map((n) => parseInt(n));

  product[key] = numbers;
}

const variableName = Object.keys({ string })[0]; // https://stackoverflow.com/a/52598270/8211893

prod.push({
  name: variableName,
  product
});

console.log(prod);

小心正则表达式,因为我忽略了管道字符。另外,我只检查分号之前的一个字符,因此您可能需要调整该表达式。

© www.soinside.com 2019 - 2024. All rights reserved.