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

JavaScript
[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
[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
[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
// Optional chaining - ES2020+ solution const getValue = (object, path) => path.reduce((value, key) => value?.[key], object); // Usage example: const myObject = { name: 'John', metadata: { type: 'json', }, }; const metadata = getValue(myObject, ['metadata', 'type']); console.log(metadata); // json
Reset
[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
[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