Create a deep (horizontal) object in a loop
I wasn't sure what the best way to word this question is but basically I'm looking to create a loop that create objects like this:
var dictionary = {};
var arr = [
["for", "item", "in", "list"],
["if", "condition"]
];
// Insert Magic Loop to yield:
dictionary.for.it开发者_C百科em.in.list // {} (exists, as well as rest of chain)
dictionary.if.condition // {} (exists, as well as rest of chain)
dictionary.for.item // {}
dictionary.test // undefined
Off the top of my head:
function create(arrArray) {
for(var i = 0; i < arrArray.length; i++) {
var arr = arrArray[i];
var _dict = dictionary;
for(var j = 0; j < arr.length; j++) {
if(!_dict[arr[j]]) {
_dict[arr[j]] = {};
}
_dict = _dict[arr[j]];
}
}
}
EDIT
Here is a subset of the solution. I wrote a function that takes in an array and a dictionary as parameters:
function create(arr, dict) {
var _dict = dict;
for(var j = 0; j < arr.length; j++) {
if(!_dict[arr[j]]) {
_dict[arr[j]] = {};
}
_dict = _dict[arr[j]];
}
}
var dictionary = {};
create(["for", "item", "in", "list"], dictionary);
create(["if", "condition"], dictionary)
If you're not worried about overwriting, you can take out the if
in the loop:
function create(arr, dict) {
var _dict = dict;
for(var j = 0; j < arr.length; j++) {
_dict[arr[j]] = {};
_dict = _dict[arr[j]];
}
}
And for better readability:
function create(arr, dict) {
var _dict = dict;
for(var j = 0; j < arr.length; j++) {
var key = arr[j];
_dict[key] = {};
_dict = _dict[key];
}
}
var dictionary = {};
var arr = [
["for", "item", "in", "list"],
["if", "condition"]
];
for(var i in arr){
var _i = arr[i];
var x = dictionary;
for(var ii in _i){
x[_i[ii]] = {};
x = x[_i[ii]];
}
}
console.log(dictionary);
console.log(dictionary.for.item.in.list);
console.log(dictionary.if.condition );
console.log(dictionary.for.item);
console.log(dictionary.test );
This will need some modification (restart at top for each sequence), but shows the general idea of descending-down:
var arr = ["foo", "if", "then", "bar"]
var dictionary = {}
var obj = dictionary // keep original
for (var i = 0; i < arr.length; i++) {
var key = arr[i]
// assign and "move to next".
// this could be done as `obj = obj[key] = {}`
obj[key] = {}
obj = obj[key]
}
Happy coding
var dictionary = {},
arr = [
["for", "item", "in", "list"],
["if", "condition"]
];
// loop the outer array
for (var x = 0; x < arr.length; x++) {
var current = dictionary, // set "current" to the top-level object (dictionary)
sub = arr[x]; // reference to sub-item
// loop sub-list
for (var y = 0; y < sub.length; y++) {
// create the new object on the "current" object,
// then assign that new object to be "current"
current = current[sub[y]] = {};
}
}
console.log(dictionary);
精彩评论