Created
October 26, 2015 19:05
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
// given a keyPath as a string assign the value | |
// to the given keyPath | |
function deepAssignment(obj, keyPath, value) { | |
//obj[keyPath] = value; //if only... | |
var path2 = keyPath.split(""); | |
var path3 = path2.map(function(char, index){ | |
if (char === "[") return isNaN(Number(path2[index+1])) ? "." : "~`~."; | |
else if (char === "]" || char === "'" || char === '"') return ""; //try splicing | |
else return char; | |
}); | |
//can be made more efficient | |
var path4 = path3.join(""); | |
var path5 = path4.split("."); | |
console.log(path5); | |
//^^^^^ | |
var final = ""; | |
path5.forEach(function(piece, index){ | |
makeArr = piece.slice(piece.length-3,piece.length) === '~`~'; | |
console.log("---making an array this time?: " + makeArr) | |
console.log("piece: " + piece) | |
if (makeArr) final += ("['" + piece.slice(0,piece.length-3) + "']"); | |
else final += ("['" + piece + "']") | |
console.log(final); | |
console.log("make new:", eval("obj" + final) === undefined, eval("obj" + final)); | |
if (index !== path5.length-1) { | |
if (eval("obj" + final) === undefined) { | |
console.log("making new:") | |
console.log("obj" + final + (makeArr ? " = []" : " = {}")) | |
if (makeArr) {console.log("SET ARRAY");eval("obj" + final + "= []");console.log("fail??");} | |
else eval("obj" + final + "= {}"); | |
} | |
} | |
else { | |
console.log("inside else") | |
console.log("obj" + final + "= value") | |
eval("obj" + final + "= value"); | |
} | |
console.log("Current: ", eval("obj"+final), "final:", final) | |
}) | |
console.log(obj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment