Skip to content

Commit c0bbd5f

Browse files
新增 README 文件內容,更新 data_get 函數以支援複合式鍵,並增加相應測試案例
1 parent d6c83d0 commit c0bbd5f

File tree

3 files changed

+53
-12
lines changed

3 files changed

+53
-12
lines changed

README.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,33 @@
1-
hi
1+
# 小工具
2+
3+
## help
4+
5+
### data_get
6+
7+
### data_set
8+
9+
### deepAssign
10+
11+
### deepClineWithJson
12+
13+
### emptyData
14+
15+
### fieldSorter
16+
17+
### gettype
18+
19+
### head
20+
21+
### parameterMerge
22+
23+
### range
24+
25+
### recursiveDeepCopy
26+
27+
### remove
28+
29+
### searchInStr
30+
31+
### strToConvert
32+
33+
### strToHump

src/help/data_get/data_get.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,15 @@ test("help.data_get object 測試 1", () => {
2828
}
2929
}
3030
expect(data_get(array, "c.d")).toStrictEqual([1, 2, 3, 4]);
31+
});
32+
33+
test("help.data_get object 測試 複合式key", () => {
34+
const array = {
35+
a: 1,
36+
b: 2,
37+
'c.d': {
38+
'd.f': [1, 2, 3, 4]
39+
}
40+
}
41+
expect(data_get(array, "c.d.d.f")).toStrictEqual([1, 2, 3, 4]);
3142
});

src/help/data_get/data_get.ts

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,32 @@ import { deepCloneWithJson, gettype } from "..";
22

33
/**
44
* 獲取資料
5-
* @param data 資料集{key:value}
5+
* @param data 資料集 {key:value}
66
* @param key 資料對應的位置 app.column.name
77
* @param defaultValue 如果取不到值要給予什麼參數,預設 null
88
* @returns
99
*
1010
* {a:[{b:a},{b:a}]}
1111
* a.b = [a,a]
1212
*/
13-
export function data_get(data: any, key: string, defaultValue: any = null,): any {
13+
export function data_get<T = any>(data: { [key: string]: any } | any[] | null | undefined, key: string, defaultValue: any = null,): T {
1414
switch (gettype(data)) {
1515
case "object":
1616
const coypData = deepCloneWithJson(data);
17-
const keys = key.split('.');
18-
let firstKey = keys.shift();
19-
if (!firstKey) return defaultValue;
20-
if (!(firstKey in coypData)) return defaultValue;
17+
const findKey = Object.keys(coypData).find((k) => key.startsWith(k));
18+
if (!findKey) return defaultValue;
2119

22-
let rep = coypData[firstKey];
23-
if (keys.length > 0)
24-
rep = data_get(rep, keys.join('.'), defaultValue);
20+
key = findKey === key ? '' : key.replace(findKey + '.', '');
21+
if (key === '') return coypData[findKey];
22+
23+
return data_get(coypData[findKey], key, defaultValue);
2524

26-
return rep ?? defaultValue;
2725
case 'undefined':
2826
case 'null':
2927
return defaultValue;
3028
case 'array':
3129
return (data as any[]).map((value: any) => data_get(value, key, defaultValue)) as any;
3230
default:
33-
return data;
31+
return data as any;
3432
}
3533
}

0 commit comments

Comments
 (0)