Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string into key value pair

I want to split the following string by comma if it matches key: value. Split by comma works until it encounters a comma in the value

const string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist"

I'd like to end up with this result:

[[country: Kenya],
[city: Nairobi],
[population: 3.375M],
[democracy-description: Work in progress/ Not fully met, obstacles exist]]

Thank you in advance.

like image 784
Nate Avatar asked Oct 22 '25 03:10

Nate


2 Answers

You could split the string by looking if not a comma follows and a colon.

var string = "country: Kenya, city: Nairobi, population: 3.375M, democracy-desciption: Work in progress/ Not fully met, obstacles exist, foo: bar, bar, bar";

console.log(string.split(/, (?=[^,]+:)/).map(s => s.split(': ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 159
Nina Scholz Avatar answered Oct 24 '25 17:10

Nina Scholz


Split into an array of key-value pair strings, then map that array to an array of arrays by splitting each pair:

const table =
 string.split(",") //["key:value","key:value"]
  .map(pair => pair.split(":")); //[["key","value"],["key","value"]]

To built an object out of this:

const result = Object.fromEntries(table);

//usable as:
console.log( result.country );

or use a Map:

const result = new Map(table);

//usable as:
console.log( result.get("country") );
like image 38
Jonas Wilms Avatar answered Oct 24 '25 16:10

Jonas Wilms