diff options
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 |
commit | f8b20adb7c599307bdff9f06ab92b9d337621b0b (patch) | |
tree | ab49e510a589e7bd199433360da565b56b4b0fc0 /src | |
parent | 0a08c0ea31fa4987a5361fdb3d0500cd549499ab (diff) |
sugar: make getNestedProp resilient against missing properties
Diffstat (limited to 'src')
-rw-r--r-- | src/common-util/sugar.js | 12 |
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))) |