1 import { isObject } from "./is-object"
2
3 /**
4 * unFlatten object keys
5 * @example
6 * input: {
7 * "variants.sku": { $like: "%-1" },
8 * "variants.prices.amount": { $gt: 30 },
9 * "variants.prices.currency": "USD"
10 * }
11 *
12 * output: {
13 * {
14 * "variants": {
15 * "sku": {
16 * "$like": "%-1"
17 * },
18 * "prices": {
19 * "amount": {
20 * "$gt": 30
21 * },
22 * "currency": "USD"
23 * }
24 * }
25 * }
26 * }
27 *
28 * @param input
29 */
30 export function unflattenObjectKeys(
31 flattened: Record<string, any>
32 ): Record<string, any> {
33 const result: Record<string, any> = {}
34
35 for (const key in flattened) {
36 if (!key.includes(".")) {
37 if (isObject(result[key])) {
38 result[key] = { ...result[key], ...flattened[key] }
39 } else {
40 result[key] = flattened[key]
41 }
42 }
43 }
44
45 for (const key in flattened) {
46 if (key.includes(".")) {
47 const value = flattened[key]
48 const keys = key.split(".")
49 let current = result
50
51 for (let i = 0; i < keys.length; i++) {
52 const part = keys[i]
53
54 if (i === keys.length - 1) {
55 if (isObject(value) && current[part]) {
56 current[part] = { ...current[part], ...value }
57 } else {
58 current[part] = value
59 }
60 } else {
61 current = current[part] = current[part] ?? {}
62 }
63 }
64 }
65 }
66
67 return result
68 }