« get me outta code hell

sugar: make getNestedProp resilient against missing properties - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/common-util/sugar.js
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2025-10-15 15:19:25 -0300
committer(quasar) nebula <qznebula@protonmail.com>2025-10-15 15:19:25 -0300
commitf8b20adb7c599307bdff9f06ab92b9d337621b0b (patch)
treeab49e510a589e7bd199433360da565b56b4b0fc0 /src/common-util/sugar.js
parent0a08c0ea31fa4987a5361fdb3d0500cd549499ab (diff)
sugar: make getNestedProp resilient against missing properties
Diffstat (limited to 'src/common-util/sugar.js')
-rw-r--r--src/common-util/sugar.js12
1 files changed, 10 insertions, 2 deletions
diff --git a/src/common-util/sugar.js b/src/common-util/sugar.js
index fd4cb59d..354cf5cc 100644
--- a/src/common-util/sugar.js
+++ b/src/common-util/sugar.js
@@ -423,15 +423,23 @@ export function splitKeys(key) {
 
 // Follows a key path like 'foo.bar.baz' to get an item nested deeply inside
 // an object. If a value partway through the chain is an array, the values
-// down the rest of the chain are gotten for each item in the array.
+// down the rest of the chain are gotten for each item in the array. If a value
+// partway through the chain is missing the next key, the chain stops and is
+// undefined (or null) at that point.
 //
 // obj: {x: [{y: ['a']}, {y: ['b', 'c']}]}
 // key: 'x.y'
 //   -> [['a'], ['b', 'c']]
 //
+// obj: {x: [{y: ['a']}, {y: ['b', 'c']}, {z: ['d', 'e']}]}
+// key: 'x.z'
+//   -> [undefined, undefined, ['d', 'e']]
+//
 export function getNestedProp(obj, key) {
   const recursive = (o, k) =>
-    (k.length === 1
+    (o === undefined || o === null
+      ? o
+   : k.length === 1
       ? o[k[0]]
    : Array.isArray(o[k[0]])
       ? o[k[0]].map(v => recursive(v, k.slice(1)))