directus

Форк
0
/
calculate-field-depth.ts 
79 строк · 1.5 Кб
1
import { isPlainObject, isArray } from 'lodash-es';
2

3
/**
4
 * Calculates the depth of a given JSON structure, not counting any _ prefixed properties
5
 *
6
 * Used to calculate the field depth in a filter or deep query structure
7
 *
8
 * @example
9
 *
10
 * ```js
11
 * const deep = {
12
 * 	translations: {
13
 * 		_filter: {
14
 * 			_and: [
15
 * 				{
16
 * 					language_id: {
17
 * 						name: {
18
 * 							_eq: 'English'
19
 * 						}
20
 * 					}
21
 * 				},
22
 * 				{
23
 * 					status: {
24
 * 						_eq: 'Published'
25
 * 					}
26
 * 				}
27
 * 			]
28
 * 		}
29
 * 	}
30
 * };
31
 *
32
 * const result = calculateFieldDepth(deep); // => 3
33
 * ```
34
 */
35
export function calculateFieldDepth(obj?: Record<string, any> | null, dotNotationKeys: string[] = []): number {
36
	if (!obj) {
37
		return 0;
38
	}
39

40
	let depth = 0;
41

42
	const keys = Object.keys(obj);
43

44
	for (const key of keys) {
45
		const nestedValue = obj[key];
46

47
		if (dotNotationKeys.includes(key) && nestedValue) {
48
			let sortDepth = 0;
49

50
			for (const sortKey of nestedValue) {
51
				if (sortKey) {
52
					sortDepth = Math.max(sortKey.split('.').length, sortDepth);
53
				}
54
			}
55

56
			if (sortDepth > depth) {
57
				depth = sortDepth;
58
			}
59
		} else {
60
			if (!isPlainObject(nestedValue) && !isArray(nestedValue)) continue;
61

62
			let nestedDepth = 0;
63

64
			if (Array.isArray(nestedValue)) {
65
				nestedDepth = Math.max(...nestedValue.map((val) => calculateFieldDepth(val, dotNotationKeys)));
66
			} else {
67
				nestedDepth = calculateFieldDepth(nestedValue, dotNotationKeys);
68
			}
69

70
			if (key.startsWith('_') === false) nestedDepth += 1;
71

72
			if (nestedDepth > depth) {
73
				depth = nestedDepth;
74
			}
75
		}
76
	}
77

78
	return depth;
79
}
80

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.