What is the best way to convert:
['[Title A]','child A','child B', '[Title B]', 'child C', 'child D']
to:
{
0: {
'title': 'Title A',
'children': ['child A', 'child B']
}
1: {
'title': 'Title B',
'children': ['Child C', 'Child D']
}
}
I have this so far which checks on the presence of brackets [] and I tried to add this to an object with a dynamic index which increments during a for loop every time a title with brackets is found:
let index = 0;
let listObject = {};
for (const listItem of listItems) {
const titleValue = listItem.match(/\[(.*?)\]/);
if (titleValue) {
++index;
listObject[index].title = titleValue[1];
} else {
listObject[index].children = [listItem];
}
}
console.log(listObject);