0

I have a string set of -

"uid:ID1,name:Name1,uid:ID2,name:Name2"

I want to map "uid:ID1,name:Name1" into

The following format

{
uid :'ID1',
name: "Name1"
}

But for it to make as many property sets as are passed in via the string set.

So for the input string with "2 sets" I need it to make this following output.

        {
            uid :'ID1',
            name: "Name1"
        },
        {
            uid :'ID2',
            name: "Name2"
        }
    

What can I try?

2 Answers 2

1

Use the main function below:

const main = str => {
  // split on each comma
  const arr = str.split(',');
  // put back elements by pairs
  const pairs = [];
  for (let i=0; i<arr.length; i+=2) {
    let o = {};
    o.uid = arr[i].split(':')[1];
    o.name = arr[i+1].split(':')[1];
    pairs.push(o);
  }
  return pairs;
}

console.log(main('uid:ID1,name:Name1'));
console.log(main('uid:ID1,name:Name1,uid:ID2,name:Name2'));

This assumes that the input string is well-formed as a repetition of uid:...,name:... (no arbitrary key, no optional key) joined by ,.

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

Comments

0

Assuming that you want Objects and the keys are arbitrary...

console.log(
  "uid:ID1,name:Name1,uid:ID2,name:Name2"
  .split(/[,:]/)
  .reduce((res, val, i, arr) => {
    if (i % 4 === 0) {
      res.push({})
    }
    if (i % 2) {
      res[res.length - 1][arr[i - 1]] = arr[i]
    }
    return res
  }, [])
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.