[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
// Custom function solution when property names can contain '.' function getValue(object, path) { return path.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', 'type']); console.log(metadata); // json
Reset