ldc-laravel-base-project/resources/ts/lib/mapPivotOptions.tsx
2026-07-09 17:32:17 +02:00

38 lines
959 B
TypeScript

import type { DefaultModel } from "@/back/types/global";
/**
* Extract ids from model relation pivot and format options
* for a multi select component.
*/
export function mapPivotOptions<T extends DefaultModel>(
model: T[],
data?: DefaultModel[],
valueKey?: keyof T,
locale?: string | null,
) {
const options = model.length
? model.map((opt) => {
const raw = valueKey ? (opt[valueKey] as unknown) : null;
return {
value: opt.id.toString(),
label:
locale && typeof raw === "object" && raw !== null
? (raw as Record<string, string>)[locale]
: (raw as string),
};
})
: [];
const defaultValue = data?.length
? data.map((item) => item.id.toString())
: [];
return { options, defaultValue };
}
export function extractIdsFromDatabasePivotRelation(
data?: DefaultModel[],
): number[] {
return data ? data.map((item) => item.id) : [];
}