Skip to content

Instantly share code, notes, and snippets.

@DLSteve
Created October 25, 2017 16:38
Show Gist options
  • Save DLSteve/1a8eed1ef8442e1a0998f6acbd06e618 to your computer and use it in GitHub Desktop.
Save DLSteve/1a8eed1ef8442e1a0998f6acbd06e618 to your computer and use it in GitHub Desktop.
Creates a nested object based on strings and values passed.
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