Skip to content

Instantly share code, notes, and snippets.

@jamischarles

jamischarles/get.js

Last active Jan 8, 2020
Embed
What would you like to do?
Rebuilding simple version of _.get()
function get(base, pathQuery, returnOnUndefinedValue) {
var pathArr = pathQuery.split('.');
var currentVal = base;
for (var i=0; i<pathArr.length; i++) {
var key = pathArr[i];
currentVal = currentVal[key];
if (!currentVal) {
return returnOnUndefinedValue ;
}
}
return currentVal;
}
// FIXME: check for window vs global myself?
// and make that the base?
// logs the part of the path that's valid... great for finding where the path goes bad...
function findValidPath(pathQuery) {
var pathArr = pathQuery.split('.')
var lastValidPath = eval(pathArr[0]) // TOOD: consider using window / global as base here instead of using eval...
// start at 1 bc we already have 0
for (var i = 1; i < pathArr.length; i++) {
var key = pathArr[i]
var nextPath = lastValidPath[key]
console.log('key', key)
console.log("lastValidPath", lastValidPath)
console.log('nextPath', nextPath)
if (!nextPath) {
// return path and value
console.log('i', i)
return {
validPath: pathArr.slice(0, i).join("."),
value: lastValidPath
}
} else {
lastValidPath = nextPath
}
}
// Whole path, bc whole path is valid...
return {
validPath: pathArr.slice(0, i).join("."),
value: lastValidPath
}
}
// test cases
var test1 = {
a: {
b: 'valid'
}
}
console.log("TEST CASE 1", findValidPath('test1.a.b')) // whole path is valid
console.log("TEST CASE 2", findValidPath('test1.a.a')) // partially valid path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment