Raw
1 type Params = {
2 obj: Record<string, unknown>
3 value: unknown
4 path: string
5 }
6
7 export default function setObjValue({
8 obj,
9 value,
10 path,
11 }: Params): Record<string, unknown> {
12 // split path by delimiter
13 const splitPath = path.split(".")
14 const targetKey = splitPath[0]
15
16 if (!Object.hasOwn(obj, targetKey)) {
17 obj[targetKey] = {}
18 }
19
20 if (splitPath.length === 1) {
21 obj[targetKey] = value
22 return obj
23 }
24
25 if (typeof obj[targetKey] !== "object") {
26 throw new Error(
27 `value of ${targetKey} is not an object, so can't set nested value`
28 )
29 }
30
31 setObjValue({
32 obj: obj[targetKey] as Record<string, unknown>,
33 value,
34 path: splitPath.slice(1).join("."),
35 })
36
37 return obj
38 }