To replace both _.get()
and _.set()
, my team has come up with these methods. We have each in its own module and export them as the default method (importing sanitizePath.js into both get.js and set.js), but they can be included in a project in a variety of ways, so I'll present them together:
let rgxBracketToDot;
export function sanitizePath (path) {
path = path || [];
return Array.isArray(path) ? path : path.replace(rgxBracketToDot || (rgxBracketToDot = /\[(\w+)\]/g), '.$1').split('.');
}
export function get (obj, path) {
if (!obj || typeof obj !== 'object') {
return;
}
return sanitizePath(path).reduce((acc, val) => acc && acc[val], obj);
}
export function set (obj, path, value) {
const [current,...rest] = sanitizePath(path);
rest.length >= 1 ? set(obj[current] = obj[current] || {}, rest, value) : obj[current]= value;
return obj;
}
Note that unlike lodash, sanitizePath()
as is won't remove leading or trailing dots (.). To remove these and ensure 100% compatibility with lodash, you'll need to include these regex replaces:
path = path.replace(/^\./, '');
path = path.replace(/\.$/, '');
For maximum performance, it's best to set the regex pattern once in a let
outside the method in a similar way as rgxBracketToDot
. As none of the paths in our codebase begin or end with a dot we removed it for our purposes.
Likewise, it's best to only use array paths to avoid having to use sanitizeString()
altogether. We plan on removing that step as well, but for the time being kept it in order to handle older config files.