January 2020
Intermediate to advanced
470 pages
11h 13m
English
Now, we can code a similar setByPath() function that will take a path, a value, and an object and update an object. This is not a pure function, but we'll use it to write a pure one; wait and see! Here is the code:
const setByPath = (arr, value, obj) => { if (!(arr[0] in obj)) { obj[arr[0]] = arr.length === 1 ? null : Number.isInteger(arr[1]) ? [] : {}; } if (arr.length > 1) { return setByPath(arr.slice(1), value, obj[arr[0]]); } else { obj[arr[0]] = value; return obj; }};
Here, we are using recursion to get into the object, creating new attributes if needed, until we have traveled the full length of the path. One important detail when creating attributes is whether we need an array or an object. We can determine ...
Read now
Unlock full access