I have this string:
posts{id,title},posts2{id,title}
I'd like to transform it to an object:
{
posts: [
'id',
'title'
],
posts2: [
'id',
'title'
]
}
How can I do this?
Given that the string will be valid with the specified format:
You can split the string into pairs of key - list items. Then, iterate over them and insert each into an object as follows:
const stringify = string => {
const obj = {};
if(string) {
const pairs = string.substring(0,string.length-1).split('},');
pairs.forEach(pair => {
const [key,value] = pair.split('{');
obj[key] = value.split(",").filter(String);
});
}
return obj;
}
console.log( stringify('posts{id,title},posts2{id,title}') );
console.log( stringify('posts{id,title}') );
console.log( stringify('posts{}') );
console.log( stringify('') );
This snippet works until you work with a 1-level object. If you need to parse nested object, you've to slightly refactor it.
const input = 'posts{id,title},posts2{id,title}';
const parse = (input) => {
return input
.replaceAll('{', '[')
.replaceAll('}', ']')
.replaceAll('],', '] , ')
.split(' , ')
.reduce((_, item) => {
const key = item.split('[')[0];
const value = item
.replace(`${key}[`, '')
.replace(']', '')
.split(',')
return {
..._,
[key]: value
};
}, {})
};
const parsed = parse(input);
Anyway I don't know what's the benefit of dealing with this notation.