-1

Can someone please help me to bring test value:

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

into below format:

   prod:[
         {
           name:test,
           product:{
                     a:[1],
                     b:[2,3],
                     c:[4,5]
                    }
          }]
1
  • 1
    What have you tried so far? Commented Apr 24, 2024 at 6:57

1 Answer 1

1

One solution could look like this:

Be careful with the regex, since I

const test = "a:1|b:2,3|c:4,5";
const regex = /(\w):([\d,]+)/gm;
const matches = test.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({ test })[0]; // https://stackoverflow.com/a/52598270/8211893

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

console.log(prod);

am ignoring the pipe character. Also I am only checking for one character before the semicolon, so you might want to adjust that expression.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.