refactor: try reduce

This commit is contained in:
sealday 2024-03-22 03:15:43 +08:00
parent e8497f8f8e
commit 25e41e479e

View File

@ -4,12 +4,6 @@ import { connect, useFieldSchema } from '@formily/react';
import { useCollectionManager, useRequest } from '@nocobase/client';
import _ from 'lodash';
interface Option {
name: string | number;
id: string;
children?: Option[];
}
const AssociationCascader = connect((props) => {
const fieldSchema = useFieldSchema();
const collection = fieldSchema['collectionName'];
@ -32,24 +26,20 @@ const AssociationCascader = connect((props) => {
});
const options = useMemo(() => {
const dict = {};
data?.data.forEach((item) => {
if (item[associationField]) {
dict[item[associationField][joinTitleField]] ??= [];
dict[item[associationField][joinTitleField]].push(item[titleField]);
}
});
const options: Option[] = [];
_.forEach(dict, (values: any, key) => {
options.push({
name: key,
id: key,
children: values.map((value) => ({
name: value,
id: value,
})),
});
});
const dict: { [key: string]: string[] } =
data?.data.reduce((acc, item) => {
if (item[associationField]) {
const key = item[associationField][joinTitleField];
acc[key] ??= [];
acc[key].push(item[titleField]);
}
return acc;
}, {}) || {};
const options = Object.entries(dict).map(([key, values]) => ({
name: key,
id: key,
children: values.map((value) => ({ name: value, id: value })),
}));
return options;
}, [associationField, joinTitleField, titleField, data?.data]);
return <Cascader options={options} {...props} showSearch />;