0

I have a following string:

var str = "name=test1^assigned_to=12345678901112131415161718991234^business_service=99945678901112131415161718991211^EQ";
var obj = { name: 'test1',
            assigned_to: '12345678901112131415161718991234',
            business_service: '99945678901112131415161718991211'
          };

and would like to create object of specific keys and values from that string as is in my example, has anyone achieved similar thing? How?

6
  • 1
    love that querystring is reinvented to use ^ as a separator. Commented Jul 28, 2020 at 14:12
  • So split on ^, loop over. Split on = and set it Commented Jul 28, 2020 at 14:13
  • Isn't short_description supposed to be name? Like it is in the string? Commented Jul 28, 2020 at 14:17
  • yes, my mistake Commented Jul 28, 2020 at 14:17
  • codepen.io/ygorbunkov/pen/QWyRarg?editors=0012 Commented Jul 28, 2020 at 14:18

1 Answer 1

1

let str = "name=test1^assigned_to=12345678901112131415161718991234^business_service=99945678901112131415161718991211^EQ";

let obj = {}
str.split('^').forEach(e => {
  let x = e.split('=');
  if (x[1])
    obj[x[0]] = x[1]
});

console.log(obj);

You can remove if (x[1]) condition;

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

1 Comment

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.