var a = ["a", "b", "c", "d"]
var res = {}
var value = "Hello"
for(var i=a.length; i > 0; i-- ){
var item = a[i-1]
var temp = {}
temp[item] = i == a.length ? value : {}
if(i != a.length){
Object.keys(res).forEach(r => {
temp[item][r] = res[r]
})
}
res = temp
}
console.log(res)
The result is :
{
"a": {
"b": {
"c": {
"d": "Hello"
}
}
}
}
Which is right, exactly what I need. I was just wondering if I'm doing it the right way or is there any better solutions for this?
Thanks in advance.
3 Answers 3
You are currently mixing declarative and functional style. I suggest succinct functional style:
var keys = ["a", "b", "c", "d"];
var value = "Hello";
var res = keys.reduceRight((value, key) => ({[key]: value}), value);
I think, iterating the array
once in the reverse order will be easy to create the nested object
from array.
Steps:
1. Iterate the array in reverse order.
2. If index is equal to the length of array then assign the value to that key.
3. For all other cases simply put the previous object inside the new key.
Check this:
var a = ["a", "b", "c", "d"];
var res = {};
var value = "Hello";
for(let i = a.length - 1; i >= 0 ; i--){
if(i == a.length - 1)
res = { [a[i]] : value}; // assign the value
else
res = { [a[i]] : res}; //put the prev object
}
console.log(res);
- Declare your variables outside the loop (or use
let
inside the loop). - The checking
i > 0
in the for loop is unnecessary asi--
will be falsy when it gets to zero anyway. This also allows you to use i as the array index instead ofi-1
- Add commas and semi-colons where appropriate.
var
a = ["a", "b", "c", "d"],
res = {},
value = "Hello",
item, temp;
for(var i=a.length; i--; ){
item = a[i], temp = {} ;
temp[item] = i == a.length-1 ? value : {} ;
if(i != a.length){
Object.keys(res).forEach(r => {
temp[item][r] = res[r] ;
})
}
res = temp ;
}
console.log(res) ;