[英]How to make plain array from nested?
這是一個數組:
let arr = [{key: 1, value: "A", children: [{key: 2, value: "B"}]}]
我試圖用元素的序列數制作簡單的列表:
let list = [{key: 1, value: "A", "num": 1}, {key: 2, value: "B", "num": "1.1"}]
我的認識是:
private productsWithNumber(products: any[]) {
const arr = [];
products.forEach((p, index: number) => {
p['num'] = index + 1;
if (p?.children) {
p.children.forEach((element, index) => {
element['num'] = `${p['num']}.${index + 1}.`;
arr.push(element);
});
}
arr.push(p);
});
return arr;
}
結果我得到了錯誤的元素順序。 如何簡化它?
您當前正在遍歷所有項目,然后遍歷子項,添加子項,然后添加父項。
您可以簡單地先添加父級以獲得正確的順序:
private productsWithNumber(products: any[]) {
const arr = [];
products.forEach((p, index: number) => {
p['num'] = index + 1;
arr.push(p); // <-- moved this line up
if (p?.children) {
p.children.forEach((element, index) => {
element['num'] = `${p['num']}.${index + 1}.`;
arr.push(element);
});
}
});
return arr;
}
任意嵌套的解決方案:
當前解決方案僅適用於 1 級嵌套children
。 如果您希望它適用於任意嵌套級別,您可以使用recursion ,例如:
type ArrayItem = {
children?: (ArrayItem | {})[]
}
const flattenChildrenArray = <T extends ArrayItem>(arr: T[], level: string | null = null): Omit<T, "children">[] => {
const tempArr: Omit<T, "children">[] = []
arr.forEach((item, index) => {
const {children, ...rest} = item;
const num = level ? `${level}.${index + 1}` : `${index + 1}`
tempArr.push({
...rest,
num,
})
if (children) {
const flattenedChildren = flattenChildrenArray(children, num) as Omit<T, "children">[]
tempArr.push(...flattenedChildren)
}
})
return tempArr;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.