1.按照一维数组顺序给二维数组排序
type Item = {};
export default function useSort(array: Item[], arraySort: string[], key: { label: string }) {
const indexMap = new Map<string, number>();
arraySort.forEach((item, index) => {
indexMap.set(item, index);
});
let keyIndex = key.label;
array.sort((a:{}, b:{}) => {
const aIndex = indexMap.get(a[keyIndex]) ?? Infinity;
const bIndex = indexMap.get(b[keyIndex]) ?? Infinity;
return aIndex - bIndex;
});
return [array];
}
使用方法:
const data: any = [
{ name: '狗牙', age: 3, sex: '女', hobby: '踢足球' },
{ name: 'Silly', age: 2, sex: '女', hobby: '打篮球' },
{ name: '狗老大', age: 2, sex: '女', hobby: '打篮球' },
{ name: 'Tom', age: 2, sex: '女', hobby: '打篮球' },
{ name: 'Lily', age: 2, sex: '女', hobby: '打篮球' }
];
const arraySort: any = ['狗老大', '狗牙', 'Lily', 'Tom', 'Silly'];
const [array] = useSort(data, arraySort, { label: 'name' });
2.自定义option字段,处理多个option数组组成的数据,根据所需过滤出来
import { Select } from 'antd';
interface Item {
[key: string]: any;
}
interface Template {
name: string;
id: string;
}
export default function useOption(array: Item[], key: string, template: Template[]) {
let selectOptionData = array.filter((item) => {
return Object.keys(item).toString() === key;
});
const Con = (value: Item[]) => {
let templateName = template[0];
let templateId = template[1];
return (
<>
{value.map((item) => {
return (
<Select.Option key={item[templateId]} value={item[templateId]}>
{item[templateName]}
</Select.Option>
);
})}
</>
);
};
return [Con, selectOptionData];
}
使用方法:
const dataOption = [
{
name: [
{ name: 'jack', id: 0 },
{ name: 'lucy', id: 1 },
{ name: 'Yiminghe', id: 2 },
{ name: 'disabled', id: 3 }
]
},
{
lily: [
{ name: 'tom', id: 0 },
{ name: 'sam', id: 1 },
{ name: 'gouya', id: 2 },
{ name: 'goulaoda', id: 3 }
]
},
{
sam: [
{ name: 'xiaodu', id: 0 },
{ name: 'wang', id: 1 },
{ name: 'li', id: 2 },
{ name: 'laowang', id: 3 }
]
}
];
let am: any = [
{ name: 'xiaodu', id: 0 },
{ name: 'wang', id: 1 },
{ name: 'li', id: 2 },
{ name: 'laowang', id: 3 }
];
const [Con, val] = useOption(dataOption, 'lily', ['name', 'id']);
<Select onChange={onChange}>{Con(am)}</Select>