I have the following array of objects with GoogleShoppingFeed-Categories:
[{
id: 914,
path: 'Bekleidung & Accessoires > Bekleidung'
},
{
id: 910,
path: 'Bekleidung & Accessoires > Bekleidung > Anzüge'
},
{
id: 2904,
path: 'Bekleidung & Accessoires > Bekleidung > Anzüge > Anzüge & Hosenanzüge'
}]
I want to split() the path string by ' > ' and build up a new array like this. The length of path array is unknown:
[{
id: 914,
path: [{
counter: 0,
partialPath: 'Bekleidung & Accessoires'
},
{
counter: 1,
partialPath: 'Bekleidung'
}
]
},{
id: 910,
path: [{
counter: 0,
partialPath: 'Bekleidung & Accessoires'
},
{
counter: 1,
partialPath: 'Bekleidung'
},
{
counter: 2,
partialPath: 'Anzüge'
}
]
},{
id: 2904,
path: [{
counter: 0,
partialPath: 'Bekleidung & Accessoires'
},
{
counter: 1,
partialPath: 'Bekleidung'
},
{
counter: 2,
partialPath: 'Anzüge'
},
{
counter: 3,
partialPath: 'Anzüge & Hosenanzüge'
}
]
},
...
]
This is my current approach:
export interface GPartialCategory {
id: number;
path: [{
counter: number;
partialPath: string;
}];
}
@Injectable()
export class CategoryService {
constructor() { }
async getAllGoogleCategories(): Promise<GPartialCategory[]> {
const repo = getRepository(GCategoryEntity, 'default');
const allCategories = await repo.find({ order: { path: 'ASC' } });
let result: any[] = [];
for (const category of allCategories) {
result.push(this.recursivePush(category));
}
return result;
}
recursivePush(category: GCategoryDto): GPartialCategory {
let result: GPartialCategory;
const fragments = category.path.split(' > ', 2);
const firstValue = fragments[0];
const rest = fragments[1];
result = ({ id: category.id, path: [{ counter: 0, partialPath: firstValue }] });
let i = 1;
while (!!rest) {
const restFragments = rest.split(' > ', 2);
const value = restFragments[0];
const nextRest = restFragments[1];
result.path.push({ counter: i, partialPath: value });
i ;
}
return result;
}
}
As you can see, this leads into JavaScript heap out of memory, because the const rest is always not empty.
Thx for any help
CodePudding user response:
I don't believe recursion is the answer here. You want to map through each path object, and create a new array inside each object. This can be done using the .map()
array method.
async getAllGoogleCategories(): Promise<GPartialCategory[]> {
const repo = getRepository(GCategoryEntity, 'default');
const allCategories = await repo.find({ order: { path: 'ASC' } });
return allCategories.map(category=>{
const pathArr = category.path.split(' > ');
const path = pathArr.map((partialPath, i)=>({counter:i, partialPath}));
return {...category, path }
})
};