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:
{
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);