Created
October 25, 2017 16:38
-
-
Save DLSteve/1a8eed1ef8442e1a0998f6acbd06e618 to your computer and use it in GitHub Desktop.
Creates a nested object based on strings and values passed.
This file contains hidden or 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
var objects = {}; | |
var array = "Address\\DeliveryPointValidationStatus\\Description".split('\\'); | |
var array2 = "Address\\DeliveryPointValidationStatus\\Code".split('\\'); | |
var array3 = "Employee\\Name".split('\\'); | |
createNestedObj(objects, array, "Bleh"); | |
createNestedObj(objects, array2, "CodeBleh"); | |
createNestedObj(objects, array3, "BigBen"); | |
console.log(objects); | |
console.log(objects.Address); | |
function createNestedObj(obj, nodes, value) { | |
var curObj; | |
for (var i = 0; i < nodes.length; i++) { | |
if (!curObj) { | |
curObj = obj; | |
} | |
if (i < nodes.length) { | |
if (i === nodes.length - 1) { | |
curObj[nodes[i]] = value; | |
} else { | |
if (!curObj[nodes[i]]) { | |
curObj[nodes[i]] = {}; | |
} | |
} | |
curObj = curObj[nodes[i]]; | |
} | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment