Last active
November 13, 2017 02:17
-
-
Save symmetriq/10200050 to your computer and use it in GitHub Desktop.
[JS] pathVar: Utility for reading/writing nested object properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Utility for reading/writing nested object properties | |
- Read: pathVar(obj, 'some.path') | |
- Write: pathVar(obj, 'some.path', newVal) | |
To automatically create the path when writing (similar to `mkdir -p`): | |
pathVar(obj, 'some.new.path', newVal, true) | |
Automatic path creation will fail if any part of the path already exists and | |
is not an object. | |
Note: This only verifies the first argument is an 'object'. Because JavaScript | |
incorrectly returns `'object'` for arrays and regular expressions, you may want | |
to replace `typeof object` with something that ensures the object is a hash. | |
*/ | |
var pathVar = (function() { | |
var iteratePath, read, write; | |
iteratePath = function(object, path, createPath) { | |
var j, len, property, tail; | |
if (createPath == null) { | |
createPath = false; | |
} | |
if (typeof object !== 'object' || typeof path !== 'string') { | |
console.error('[pathVar] invalid arguments'); | |
return Array(2); | |
} | |
if (path.indexOf('.') === -1) { | |
return [object, path]; | |
} | |
path = path.split('.'); | |
tail = path.pop(); | |
for (j = 0, len = path.length; j < len; j++) { | |
property = path[j]; | |
if (!object.hasOwnProperty(property)) { | |
console.log(createPath); | |
if (!createPath) { | |
return Array(2); | |
} | |
object[property] = {}; | |
} | |
object = object[property]; | |
} | |
return [object, tail]; | |
}; | |
read = function(object, path) { | |
var key, parentObj, ref; | |
ref = iteratePath(object, path), parentObj = ref[0], key = ref[1]; | |
if (parentObj && key) { | |
return parentObj[key]; | |
} | |
}; | |
write = function(object, path, value, createPath) { | |
var key, parentObj, ref; | |
if (createPath == null) { | |
createPath = false; | |
} | |
ref = iteratePath(object, path, createPath), parentObj = ref[0], key = ref[1]; | |
if (!(parentObj && key)) { | |
return; | |
} | |
parentObj[key] = value; | |
return value; | |
}; | |
return function(object, path, value, createPath) { | |
var ref; | |
if (createPath == null) { | |
createPath = false; | |
} | |
if (arguments.length === 2) { | |
return read(object, path); | |
} | |
if ((ref = arguments.length) === 3 || ref === 4) { | |
return write(object, path, value, createPath); | |
} | |
return console.error('[pathVar] incorrect number of arguments'); | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment