I'm looking to take a hash, create a deep series of keys and then append another hash to the end.
given...
var hash_a = {'foo': 'bar'}
var hash_b = {'alpha': 'beta'}
var array = ['a', 'b', 'c']
how can I generate the following?
{
'foo': 'bar',
'a':{
'b':{
'c': {
'alpha': 'beta'
}
}
}
};
This should do the trick:
var hash_a = {'foo': 'bar'};
var hash_b = {'alha': 'beta'};
var array = ['a', 'b', 'c'];
function build(a,b,c){
var o=c.reduceRight(function(o, n){ var b={}; b[n]=o; return b; }, b);
for(x in a){ o[x]=a[x]; }
return o;
}
Here is the fiddle to play with.
See MDN for further explanation of Array.prototype.reduceRight()
.