diff --git a/src/internal/components/option/utils/unflatten-options.ts b/src/internal/components/option/utils/unflatten-options.ts index db8a72da01..69fc842959 100644 --- a/src/internal/components/option/utils/unflatten-options.ts +++ b/src/internal/components/option/utils/unflatten-options.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { DropdownOption } from '../interfaces'; +import { DropdownOption, OptionGroup } from '../interfaces'; interface ParentDropdownOption { type: 'parent'; @@ -20,17 +20,21 @@ export type NestedDropdownOption = ParentDropdownOption | ChildDropdownOption; export function unflattenOptions(options: ReadonlyArray): NestedDropdownOption[] { const nestedOptions: NestedDropdownOption[] = []; - let currentParent: ParentDropdownOption | undefined; + + const attachedChildren = new Set(); options.forEach((option, index) => { if (option.type === 'parent') { const wrapped: ParentDropdownOption = { type: 'parent', option, index, children: [] }; - currentParent = wrapped; + (option.option as OptionGroup).options.forEach(child => { + const childOption = options.find(o => o.type === 'child' && o.option.value === child.value); + if (childOption) { + wrapped.children.push({ type: 'child', option: childOption, index }); + attachedChildren.add(childOption); + } + }); nestedOptions.push(wrapped); - } else if (!option.type || option.type === 'child') { - (currentParent?.children ?? nestedOptions).push({ type: 'child', option, index }); - } else { - currentParent = undefined; + } else if (!attachedChildren.has(option)) { nestedOptions.push({ type: 'child', option, index }); } });