I'm trying to convert array of strings with dots between names. I want to make an array of object like in const out. I tried to make it by reduceRight, but I don't know how to combine fields.
My code:
const input = ['apples', 'bananas.kivi.grape', 'bananas.orange', 'bananas.strawberry'];
const res = input.map((item) => {
const splInp = item.split('.');
return splInp.reduceRight((acc, item) => {
if (Object.keys(acc).length !== 0) {
return {
children: [acc],
"name": item
};
} else {
return {
"name": item
};
}
}, []/* as any*/);
});
console.log(res);
Desired output:
const out = [
{ name: 'apples' },
{
name: 'bananas',
children: [
{
name: 'kivi',
children: [
{
name: 'grape',
},
],
},
{ name: 'orange' },
{ name: 'strawberry' },
],
},
];