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