Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse string of key value pairs where key occurs multiple times into object

I have a string in the following format:

"foo: bar, foo: baz, some: thing, some: other, third: other"

And what i want is an object:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ 
  foo: [bar, baz],
  some: [other, thing],
  third: [other]
}

How could I achieve this in a smart way?

>Solution :

You can simply split on , leaving you with the key value pairs. Then you can split each pair on : and then add the key into an object and store the values in an array.

let str = "foo: bar, foo: baz, some: thing, some: other, third: other";

let obj = {};
str.split(", ").forEach((pair) => {
    let [key, value] = pair.split(": ");
  if (obj[key]) {
    obj[key].push(value);
  } else {
    obj[key] = [value];
  }
});
console.log(obj);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading