我有以下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'/span>。
}]
我想用'>'分割()路徑字串并建立一個新的陣列,像這樣。路徑陣列的長度是未知的:
[{
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'.
}
]
},
...
這是我目前的方法:
export 介面GPartialCategory {
id: 數字。
path: [{
counter: 數字。
partialPath: string;
}];
}
@Injectable()
export class CategoryService {
constructor() { }
async getAllGoogleCategories()。Promise<GPartialCategory[]> {
const repo = getRepository(GCategoryEntity, 'default')。
const allCategories = await repo.find({ order: { path: 'ASC' }; ;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(' > '/span>, 2)。
const value = restFragments[0] 。
const nextRest = restFragments[1] 。
result.path.push({ counter: i, partialPath: value })。
i ;
}
return result;
}
}
正如你所看到的,這導致了JavaScript堆的記憶體不足,因為const rest總是不空。
謝謝您的幫助
uj5u.com熱心網友回復:我不相信遞回是這里的答案。你想通過每個路徑物件進行映射,并在每個物件中創建一個新的陣列。這可以用.map()陣列方法來完成。
async getAllGoogleCategories()。Promise<GPartialCategory[]> {
const repo = getRepository(GCategoryEntity, 'default')。
const allCategories = await repo.find({ order: { path: 'ASC' }; ;path: 'ASC' } });
return allCategories.map(category=> {
const pathArr = category.path.split(' > ')。
const path = pathArr. map((partialPath, i)=>({counter:i, partialPath}) 。)
return {...category, path })
})
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/319324.html
標籤:
