[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 21 22 23 24 25// custom function solution when property names don't contain '.' function getValue$1(object, key) { return object == null ? object : object[key]; } function getValue$2(object, path) { return path.split('.').reduce(getValue$1, object); } // Usage example: var myObject = { name: 'John', metadata: { type: 'json', }, }; var metadata = getValue$2(myObject, 'metadata'); var type = getValue$2(myObject, 'metadata.type'); console.log(metadata); // { type: 'json' } console.log(type); // json
Reset