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

Time:07-15

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?

CodePudding user response:

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

CodePudding user response:

First, we have to split the array based on commas for that, we can use

const commaSepArray = "foo: bar, foo: baz, some: thing, some: other, third: other".split(",")

so commaSepArray will have  

['foo: bar', ' foo: baz', ' some: thing', ' some: other', ' third: other'] // which looks like a key-value pair , now we have to split it again and create an object like

const Obj = {}

commaSepArray.map((x)=>{
   const keyVal =  x.split(":"); 
    if(Obj[keyVal[0]]){
       Obj[keyVal[0]].push(keyVal[1]) 
    }else {
       Obj[keyVal[0]] = [keyVal[1]]  
    }
})

CodePudding user response:

I think this is the answers:

const string = "foo: bar, foo: baz, some: thing, some: other, third: other"
const splitString = string.split(', ');
let obj = {}

// assign every key to the object and set the value to an empty array
splitString.forEach((string) => {
  const innerSplitString = string.split(': ');
  obj[innerSplitString[0]] = []
})

// push every value into the [key]-[empty array value] of the object
splitString.forEach((string) => {
  const innerSplitString = string.split(': ');
  obj[innerSplitString[0]].push(innerSplitString[1])
})

// sort the [key]-[array value]
for(const key in obj) {
  obj[key].sort()
}

console.log(obj)

I hope this will help you, thank you

  • Related