This topic created in 1406 days ago, the information mentioned may be changed or developed.
//header: {a: "sss", b: "京津冀"}
// data: [{a: "迭代", b: "迭代"},{a: "测试", b: "测试"}, {a: "哦哦", b: "偶偶"}]
// 整合数据和表头
const json = concatHeaderAndData(header, data);
//json: [{sss: "迭代", 京津冀: "迭代"}
// {sss: "迭代", 京津冀: "迭代"}
// {sss: "哦哦", 京津冀: "偶偶"}]
const concatHeaderAndData = (header: {}, data: any[]) => {return........}
(header: {}, data: any[])这里的数据类型该怎么写,header 里对象不固定
Supplement 1 · Jul 20, 2022
加了下面一段代码后,无论哪个定义的类型都会报错
const concatHeaderAndData = (header: any, data:any[]) => {
return data.map((item) => {
return Object.keys(item).reduce((newData, key) => {
const newKey = header[key] || key;
newData[newKey] = item[key];
return newData;
}, {});
});
};
10 replies • 2022-07-21 02:04:10 +08:00
 |
|
1
SilentDepth Jul 20, 2022 1
function concatHeaderAndData <H, D>(header: H, data: D) { /* ... */ }
|
 |
|
2
AlphaTr Jul 20, 2022 2
concatHeaderAndData<K extends string | number | symbol, T extends string | number | symbol, S extends Record<K, any>>(h: Record<K, T>, d: Array<S>): Array<Record<T, S[keyof S]>> 不知道是不是这个意思
|
 |
|
4
yazoox Jul 20, 2022
interface Header { [key: string]: string | number; // or using 'any' as type directly }
const concatHeaderAndData = (header: Header, data: Array<Header>) => { // }
|
 |
|
6
particlec Jul 20, 2022
补充了一些业务逻辑,然后发现上面定义的类型全部都会标红 const concatHeaderAndData = (header: any, data:any[]) => { return data.map((item) => { return Object.keys(item).reduce((newData, key) => { const newKey = header[key] || key; newData[newKey] = item[key]; return newData; }, {}); }); };
|
 |
|
7
duan602728596 Jul 20, 2022 1
type Item = Record<string, string>;
const headers: Item = { a: 'sss', b: '京津冀' };
const data: Array<Item> = [ { a: '迭代', b: '迭代' }, { a: '测试', b: '测试' }, { a: '哦哦', b: '偶偶' } ];
const concatHeaderAndData = (header: Item, data: Array<Item>): Array<Item> => { return data.map((item: Item): Item => { return Object.keys(item).reduce((newData: Item, key: string): Item => { const newKey = header[key] || key; newData[newKey] = item[key]; return newData; }, {}); }); };
|
 |
|
10
chenzhe Jul 21, 2022 via iPhone
有个网站可以吧数据结构复制进去然后自动生成类型,忘记网址了。你可以搜一搜 顺便楼内等大佬解答 哈哈哈
|