1
0
Fork 0
mirror of synced 2024-06-29 03:20:34 +12:00

Update deepSet helper to create parent keys of a deep path if one does not exist

This commit is contained in:
Andrew Kingston 2021-12-10 15:27:04 +00:00
parent f4c3435e98
commit 989310c29a

View file

@ -37,6 +37,8 @@ export const deepGet = (obj, key) => {
* Exact matches of keys with dots in them take precedence over nested keys of
* the same path - e.g. setting "a.b" of { "a.b": "foo", a: { b: "bar" } }
* will override the value "foo" rather than "bar".
* If a deep path is specified and the parent keys don't exist then these will
* be created.
* @param obj the object
* @param key the key
* @param value the value
@ -51,7 +53,14 @@ export const deepSet = (obj, key, value) => {
}
const split = key.split(".")
for (let i = 0; i < split.length - 1; i++) {
obj = obj?.[split[i]]
const nextKey = split[i]
if (obj && obj[nextKey] == null) {
obj[nextKey] = {}
}
obj = obj?.[nextKey]
}
if (!obj) {
return
}
obj[split[split.length - 1]] = value
}