[Edit]
+
0
-
0

JavaScript - get nested property value by path (resistant to null/undefined)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// Optional chaining (ES2020) with function overloading: const getValue$1 = (object, path) => path.reduce((value, key) => value?.[key], object); const getValue$2 = (object, path) => getValue$1(object, path.split('.')); // Usage example: const myObject = { name: 'John', metadata: { type: 'json', }, }; const metadata1 = getValue$1(myObject, ['metadata', 'type']); const metadata2 = getValue$2(myObject, 'metadata.type'); console.log(metadata1); // json console.log(metadata2); // json
Reset