November 2017
Intermediate to advanced
386 pages
9h 22m
English
Back in the Getting a property from an object section in Chapter 6, Producing Functions - Higher-Order Functions, we wrote a simple getField() function that could handle getting a single attribute out of an object.
const getField = attr => obj => obj[attr];
We could get a deep attribute out of an object by composing a series of applications of getField()calls, but that would be rather cumbersome. Rather, let's have a function that will receive a path -an array of field names- and will return the corresponding part of the object, or will be undefined if the path doesn't exist. Using recursion is quite appropriate and simplifies coding!
const getByPath = (arr, obj) => { if (arr[0] in obj) { return arr.length > 1 ? getByPath(arr.slice(1), ...