1 import { isObject } from "./is-object"
2
3 /**
4 * Converts a structure of find options to an
5 * array of string paths
6 * @example
7 * // With `includeTruePropertiesOnly` default value set to false
8 * const result = objectToStringPath({
9 * test: {
10 * test1: true,
11 * test2: true,
12 * test3: {
13 * test4: true
14 * },
15 * },
16 * test2: true
17 * })
18 * console.log(result)
19 * // output: ['test', 'test.test1', 'test.test2', 'test.test3', 'test.test3.test4', 'test2']
20 *
21 * @example
22 * // With `includeTruePropertiesOnly` set to true
23 * const result = objectToStringPath({
24 * test: {
25 * test1: true,
26 * test2: true,
27 * test3: {
28 * test4: true
29 * },
30 * },
31 * test2: true
32 * }, {
33 * includeTruePropertiesOnly: true
34 * })
35 * console.log(result)
36 * // output: ['test.test1', 'test.test2', 'test.test3.test4', 'test2']
37 *
38 * @param {InputObject} input
39 * @param {boolean} includeParentPropertyFields If set to true (example 1), all properties will be included as well as the parents,
40 * otherwise (example 2) all properties path set to true will included, excluded the parents
41 */
42 export function objectToStringPath(
43 input: object = {},
44 { includeParentPropertyFields }: { includeParentPropertyFields: boolean } = {
45 includeParentPropertyFields: true,
46 }
47 ): string[] {
48 if (!isObject(input) || !Object.keys(input).length) {
49 return []
50 }
51
52 const output: Set<string> = includeParentPropertyFields
53 ? new Set(Object.keys(input))
54 : new Set()
55
56 for (const key of Object.keys(input)) {
57 if (isObject(input[key])) {
58 const deepRes = objectToStringPath(input[key], {
59 includeParentPropertyFields,
60 })
61
62 const items = deepRes.reduce((acc, val) => {
63 acc.push(`${key}.${val}`)
64 return acc
65 }, [] as string[])
66
67 items.forEach((item) => output.add(item))
68 continue
69 }
70
71 if (isObject(key) || input[key] === true) {
72 output.add(key)
73 }
74 }
75
76 return Array.from(output)
77 }