Skip to content

Instantly share code, notes, and snippets.

@btsuhako
Last active August 11, 2016 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btsuhako/b9414c36ba70f47b2efe14fb8ee725d4 to your computer and use it in GitHub Desktop.
Save btsuhako/b9414c36ba70f47b2efe14fb8ee725d4 to your computer and use it in GitHub Desktop.
reimplement lodash.get()
// basic reimplementation of https://lodash.com/docs#get
var util = require('util')
var obj1 = {
'a': {
'b': {
'c': 1
}
}
}
var obj2 = {
'a': [{
'b': {
'c': 2
}
},{
'b': {
'c': 3
}
}]
}
var pathA = 'a.b.c'
var pathB = 'a[0].b.c'
var pathC = 'a[1].b.c'
var get = function(object, path, defaultValue) {
if (typeof(path) === 'string') {
var paths = path.split('.')
var current = object
var returnValue = defaultValue
var regex = /(\w+)\[(\d+)\]/g
var result = paths.every(function(currentValue, index, array) {
// regex to see if currentValue is an array index
var matches = regex.exec(currentValue)
var next
// check to see if path is an array reference. if true then
// match[1] is the object name
// match[2] is the array index
if (matches && current[matches[1]][matches[2]]) {
next = current[matches[1]][matches[2]]
}
// we don't have an array, just an object name
else if (current[currentValue]) {
next = current[currentValue]
}
if (next) {
current = next
returnValue = current
return true
}
else {
returnValue = defaultValue
return false
}
})
return returnValue
} else if (util.isArray(path)) {
// TODO
} else {
return defaultValue;
}
}
console.log(get(obj1, pathA, 'hello world'))
console.log(get(obj2, pathB, 'hello world'))
console.log(get(obj2, pathC, 'hello world'))
console.log(get(obj1, pathC, 'hello world'))
console.log(get(obj1, pathC))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment